Re: bash history

2024-07-28 Thread Mike Castle
On Sun, Jul 28, 2024 at 5:16 AM songbird  wrote:
>   not that i would want that,
>
>   but it would be possible for various terminals to save to
> their own unique history files based upon terminal pty or
> tty or anything else you'd like and to reload those upon
> starting up again.

Yes.

Setting HISTFILE is one way to control that.  It is not uncommon for
folks to do something like:
HISTFILE=~/.history.${HOSTNAME}

when using a shared file system (e.g., NFS).

In bash, the history built-in takes a filename for most options.  So
you can do something like:
history -r ~/.history.project

to load a curated set of helpful commands (though at that point, shell
scripts may start to be more useful)

mrc



Re: bash history

2024-07-28 Thread Mike Castle
On Sat, Jul 27, 2024 at 11:23 PM Jeffrey Walton  wrote:
> On Sun, Jul 28, 2024 at 12:25 AM Mike Castle  wrote:
> > * I keep history under source control (currently git) and regularly
> > (well, for some definition of "regularly"), merge them across machines
>
> This is an unusual use case (to me). Why do you save history in a
> version control system?

I rarely have raw data that needs backing up, so I don't do it on a
system level.  At work, all important data is in SCM, and various
managed systems.  At home, everything I care about is in SCM
(including history) and that repo is backed up.

Also, it allows merging between the machines.  Back when almost every
machine I used had $HOME on NFS, this was less of an issue.

> Out of curiosity, do you scrub the file regularly for credentials,
> like usernames and passwords, and remove entries?

I never enter credentials via the command line.  This is something I
picked up before Linux even existed.

In addition to history, they are viewable via ps(1).  While many
modern systems may allow programs to scrub their command line, few
programs do it, and a wrapper script that just passes it along likely
can't.

But, I have trimmed out the occasional cat-walking-across-the-keyboard
and falling-asleep-faceplant-and-drooling-on-the-keyboard type of
history.

mrc



Re: bash history

2024-07-28 Thread Mike Castle
On Sat, Jul 27, 2024 at 11:04 PM mick.crane  wrote:
> If I've "su'd" I type "exit".
> To close the terminal I click that X in the virtual terminal's top right
> hand corner.

Depending on settings, that may or may not save that invocation's
history.  You'll likely want to test to verify that it does what you
want.  But, as Greg pointed out, C-d or "exit" will generally ensure
the right thing happens.  If you weren't aware, C-d is the traditional
terminal setting for end-of-file (EOF).  It is a system level setting
to indicates no further input is coming into this terminal, which
causes the shell to exit.

mrc



Re: bash history

2024-07-28 Thread The Wanderer
On 2024-07-28 at 09:29, Yassine Chaouche wrote:

> Le 7/28/24 à 12:19, songbird a écrit :
> 
>> to keep my own setup consistent and to not keep certain things in
>> history i actually do the opposite of what you want because i want
>> certain commands already preloaded in my history for all windows
>> when i start up and then i adjust my environment based upon which
>> pty or directory i'm in.
> 
> I'm scratching my head here.
> 
> Can anyone provide a solid example or reason why preloading commands
> in history is necessary?

It's never *necessary*, AFAIK, but it *is* often convenient. (And in
many things, convenience is *the* deciding factor.)

It's often *far* easier to repeat a lengthy command from history (e.g.
via Ctrl+R and typing part of the command), either verbatim or with
modifications, than by retyping it from scratch. I rely on this
extensively - more in my terminal-based SQL-database interaction
sessions than in the shell itself, because the commands there are far
more complex than those in the shell, but I certainly do also rely on it
in the shell.

If you expect to want to use similar commands repeatedly over multiple
shell sessions, why wouldn't you want them there in the history for
ready access?

-- 
   The Wanderer

The reasonable man adapts himself to the world; the unreasonable one
persists in trying to adapt the world to himself. Therefore all
progress depends on the unreasonable man. -- George Bernard Shaw



signature.asc
Description: OpenPGP digital signature


Re: bash history

2024-07-28 Thread Yassine Chaouche

Le 7/28/24 à 12:19, songbird a écrit :
[...] 
   to keep my own setup consistent and to not keep certain

things in history i actually do the opposite of what you
want because i want certain commands already preloaded in
my history for all windows when i start up and then i adjust
my environment based upon which pty or directory i'm in.


I'm scratching my head here.
Can anyone provide a solid example or reason why preloading commands in history 
is necessary?

Best,

--
yassine -- sysadm
+213-779 06 06 23
http://about.me/ychaouche
Looking for side gigs.



Re: bash history

2024-07-28 Thread songbird
mick.crane wrote:

> In debian bookworm, xfce desktop, different virtual terminals have a 
> different history if same user presses "up key" in different virtual 
> terminals ?
> Is this something that can be changed so history is shared between 
> virtual terminals?
> mick

  not that i would want that,

  but it would be possible for various terminals to save to
their own unique history files based upon terminal pty or
tty or anything else you'd like and to reload those upon
starting up again.

  to keep my own setup consistent and to not keep certain
things in history i actually do the opposite of what you
want because i want certain commands already preloaded in
my history for all windows when i start up and then i adjust
my environment based upon which pty or directory i'm in.

  i also consider it a security or privacy leak to keep
some information in history files of any kind so those get
cleaned up upon normal shutdowns or start ups.


  songbird



Re: bash history

2024-07-28 Thread Yassine Chaouche




Le 7/28/24 à 05:24, Mike Castle a écrit :

On Sat, Jul 27, 2024 at 2:50 PM mick.crane  wrote:

Is this something that can be changed so history is shared between
virtual terminals?


Yes.

[...]

From my .bashrc file, I have the following history related settings:
   # No limit on running shell history size
   HISTSIZE=-1
   # No limit on lines saved in history file
   HISTFILESIZE=-1
   # Enable timestamps in bash_history
   HISTTIMEFORMAT="[%F %T %z] "
   # Stop history being clobbered if there are multiple shells open
   shopt -s histappend
   # Immediately append history
   PROMPT_COMMAND='history -a'

If you really want to try sharing history immediately between shells, use this:
   PROMPT_COMMAND='history -a; history -n'

Note that PROMPT_COMMAND executes before printing a prompt, which
means after executing a command.  So, if using "history -n", then
other shells will not load the shared history until a new prompt is
printed (e.g., hitting the ENTER key to display a new prompt).

For the record, I deal with the expected conflicts when merging
history files across machines by using a simple python program that
parses the history file (that includes the timestamps), discards the
conflict markers, orders by timestamps, and writes it back out.  It is
by no means perfect, but "good enough for me".

For those worried about the unbounded history, I started doing that
about ten years ago and my work history is currently just shy of
180,000 commands.  It would likely be less if I turned on the
"erasedups" feature, but I like to keep the context.  And I've seen
comments about folks who have multiple decades of shell history.  On
modern machines, it simply isn't an issue.

mrc


I second Mike Castle on this.

I have more or less the same config for my bash:

export HISTSIZE=-1 # write all commands to history file
export HISTTIMEFORMAT="%Y/%m/%d %H:%M:%S "
export HISTFILESIZE=-1 #don't truncate
export PROMPT_COMMAND="history -a; history -n" # [a]ppend commands to histfile 
immedatly,
   # and read [n]ew entries (could 
be written from other terminals)

The PROMPT_COMMAND is where the magic happens:
Every time you press Enter,
your command is instantly recorded to the history file with history -a,
instead of waiting until bash exits properly.
This ensures you never lose track of any command,
even if your bash session ends unexpectedly.
Additionally, history -n allows your shell to read the bash history again,
updating it with any new entries.

Imagine executing foo in terminal 1,
pressing Enter,
then switching to terminal 2.
By simply pressing Enter again and hitting the Up arrow,
you'll get the command foo.

This seamless synchronization across terminals enhances my productivity by 
ensuring all terminals are always in sync.

Best,


--
yassine -- sysadm
+213-779 06 06 23
http://about.me/ychaouche
Looking for side gigs.



Re: bash history

2024-07-28 Thread mick.crane

On 2024-07-27 23:58, Greg Wooledge wrote:


You need to specify *exactly* what you're doing.


"exactly" is at mickiwiki.com
I can take the ridicule of my coding understanding.


Whenever I need to reboot my computer (kernel update or the like), I
decide which shells I want to retain history from, and I exit from 
those

cleanly (^D).


that's useful



Re: bash history

2024-07-28 Thread Jeffrey Walton
On Sun, Jul 28, 2024 at 12:25 AM Mike Castle  wrote:
>
> On Sat, Jul 27, 2024 at 2:50 PM mick.crane  wrote:
> > Is this something that can be changed so history is shared between
> > virtual terminals?
>
> [...]
> For me, I see up bash with the following features:
> * Unbounded history
> * History is immediately saved to disk after each command finishes
> * I keep history under source control (currently git) and regularly
> (well, for some definition of "regularly"), merge them across machines

This is an unusual use case (to me). Why do you save history in a
version control system?

> [...]
> For the record, I deal with the expected conflicts when merging
> history files across machines by using a simple python program that
> parses the history file (that includes the timestamps), discards the
> conflict markers, orders by timestamps, and writes it back out.  It is
> by no means perfect, but "good enough for me".
>
> For those worried about the unbounded history, I started doing that
> about ten years ago and my work history is currently just shy of
> 180,000 commands.  It would likely be less if I turned on the
> "erasedups" feature, but I like to keep the context.  And I've seen
> comments about folks who have multiple decades of shell history.  On
> modern machines, it simply isn't an issue.

Out of curiosity, do you scrub the file regularly for credentials,
like usernames and passwords, and remove entries?

Jeff



Re: bash history

2024-07-28 Thread mick.crane

On 2024-07-28 02:12, Greg Wooledge wrote:

On Sun, Jul 28, 2024 at 02:01:04 +0100, mick.crane wrote:

On 2024-07-27 23:58, Greg Wooledge wrote:
> You need to specify *exactly* what you're doing.


Sometimes I forget where I was after closing a virtual terminal  and 
it

would be handy to see the history
in a new terminal, where I "cd'd" to for example.
stuff like that.


No, I mean *how did you close the terminal*?  And what terminal is it?


one of these
1826 ?Sl 0:00 xfce4-terminal
1854 pts/0    Ss 0:00 bash

If I've "su'd" I type "exit".
To close the terminal I click that X in the virtual terminal's top right 
hand corner.




Re: bash history

2024-07-27 Thread Mike Castle
On Sat, Jul 27, 2024 at 2:50 PM mick.crane  wrote:
> Is this something that can be changed so history is shared between
> virtual terminals?

Yes.

There are all sorts of settings that can control how shells save
history.  Most shells are capable of doing whatever you want, but the
default configuration is likely different across each one (bash vs ksh
vs zsh vs csh), and what values you need to change to achieve what you
want varies between them as well.

Everything you need should be available through the install manual
pages, accessible via the command "man bash".  Searching for "history"
will turn up a lot of information.  The same information, organized
differently and likely different examples, is available via "info
bash" if you install the "bash-doc" package, and that same
documentation is available online at
https://www.gnu.org/software/bash/manual/ .  All forms have a section

If I'm not mistaken, by default bash has the following settings:
* Each invocation bash loads the existing history file into memory
* Each invocation keeps the last 500 commands while open
* As each invocation closes, it writes out its own history,
overwriting this existing history (e.g., the last one to exit wins)

You can verify the above yourself by opening two terminal and running
commands different command in them like:
# In one terminal
echo I am shell one

# In the other term
echo I am shell two

Then exit the shells and open up a new one, and running the command:
history | tail

to see what was saved and in what order.

You should experiment with the various settings listed in the
documentation and see what works for you for day-to-day usage.

For me, I see up bash with the following features:
* Unbounded history
* History is immediately saved to disk after each command finishes
* I keep history under source control (currently git) and regularly
(well, for some definition of "regularly"), merge them across machines

For a while, I did experiment with "immediately sharing history
between running shells."  That lasted about three months, then I gave
up on the immediate-sharing, but kept the immediate-saving.

>From my .bashrc file, I have the following history related settings:
  # No limit on running shell history size
  HISTSIZE=-1
  # No limit on lines saved in history file
  HISTFILESIZE=-1
  # Enable timestamps in bash_history
  HISTTIMEFORMAT="[%F %T %z] "
  # Stop history being clobbered if there are multiple shells open
  shopt -s histappend
  # Immediately append history
  PROMPT_COMMAND='history -a'

If you really want to try sharing history immediately between shells, use this:
  PROMPT_COMMAND='history -a; history -n'

Note that PROMPT_COMMAND executes before printing a prompt, which
means after executing a command.  So, if using "history -n", then
other shells will not load the shared history until a new prompt is
printed (e.g., hitting the ENTER key to display a new prompt).

For the record, I deal with the expected conflicts when merging
history files across machines by using a simple python program that
parses the history file (that includes the timestamps), discards the
conflict markers, orders by timestamps, and writes it back out.  It is
by no means perfect, but "good enough for me".

For those worried about the unbounded history, I started doing that
about ten years ago and my work history is currently just shy of
180,000 commands.  It would likely be less if I turned on the
"erasedups" feature, but I like to keep the context.  And I've seen
comments about folks who have multiple decades of shell history.  On
modern machines, it simply isn't an issue.

mrc



Re: bash history

2024-07-27 Thread Max Nikulin

On 28/07/2024 08:01, mick.crane wrote:
Sometimes I forget where I was after closing a virtual terminal  and it 
would be handy to see the history

in a new terminal, where I "cd'd" to for example.


help history
less ~/.bash_history




Re: bash history

2024-07-27 Thread Greg Wooledge
On Sun, Jul 28, 2024 at 02:01:04 +0100, mick.crane wrote:
> On 2024-07-27 23:58, Greg Wooledge wrote:
> > You need to specify *exactly* what you're doing.

> Sometimes I forget where I was after closing a virtual terminal  and it
> would be handy to see the history
> in a new terminal, where I "cd'd" to for example.
> stuff like that.

No, I mean *how did you close the terminal*?  And what terminal is it?

In the ideal scenario, if you closed the terminal by pressing Ctrl-D
in the shell, the history should be written to disk.  Then, opening a
new terminal+shell should read that history into memory.  You should be
able to search the previous shell's history in that new shell.

There are lots of ways this could fail.  For example, you might be
closing the terminal window by using a window manager control button,
or by running the xkill(1) program and then clicking the window.

Or, you might have too many history lines in memory at the time you
exit the shell, and the cd command that you wanted to find might be
dropped because it was too far in the past.  (Bash only stores 500
lines of history by default.)



Re: bash history

2024-07-27 Thread mick.crane

On 2024-07-27 23:58, Greg Wooledge wrote:


You need to specify *exactly* what you're doing.


My project management skills are non-existent.
If I have a script that is working I'll copy to eg. script2 and make 
changes to that.
Sometimes, depending, I'll have similar things in other directories that 
I"ll use bits of.
Mainly using different windows Ctrl+Alt+arrows in Xfce with their own 
virtual terminals.
Sometimes I forget where I was after closing a virtual terminal  and it 
would be handy to see the history

in a new terminal, where I "cd'd" to for example.
stuff like that.



If you close a terminal emulator in such a way that it kills the shell
without letting the shell write history to disk, then the history will
not be saved.

If you want history to be saved, you should exit from the *shell*
(e.g. by pressing Ctrl-D), rather than closing the terminal and 
counting

on that to terminate the shell in a way that will preserve history.

If you *don't* want history to be saved, there are many ways to make
that (not) happen, depending on your terminal emulator and so on.  
You'll

need to experiment, though, to see exactly what happens when you do
whatever it is you do.

Whenever I need to reboot my computer (kernel update or the like), I
decide which shells I want to retain history from, and I exit from 
those

cleanly (^D).  I leave the others running, and exit from FVWM, which
kills them in a way that causes their history not to be written.

If you want a particular shell window's history to be AGGRESSIVELY
written to disk every time you run a command, you can arrange for that
as well.  See  for example.




Re: bash history

2024-07-27 Thread Vincent Lefevre
On 2024-07-27 22:50:17 +0100, mick.crane wrote:
> In debian bookworm, xfce desktop, different virtual terminals have a
> different history if same user presses "up key" in different virtual
> terminals ?
> Is this something that can be changed so history is shared between virtual
> terminals?

This is possible with zsh (option SHARE_HISTORY). But I do not use
this option: if I want to retrieve a command from another terminal,
I simply re-execute the shell to get the whole history of commands
typed so far (but there are other ways to manipulate the history).

-- 
Vincent Lefèvre  - Web: 
100% accessible validated (X)HTML - Blog: 
Work: CR INRIA - computer arithmetic / AriC project (LIP, ENS-Lyon)



Re: bash history

2024-07-27 Thread The Wanderer
On 2024-07-27 at 18:44, mick.crane wrote:

> On 2024-07-27 23:08, Greg Wooledge wrote:
> 
>> On Sat, Jul 27, 2024 at 22:50:17 +0100, mick.crane wrote:
>> 
>>> In debian bookworm, xfce desktop, different virtual terminals
>>> have a different history if same user presses "up key" in
>>> different virtual terminals ?
>> 
>> As your subject says, this is "bash history".  And yes, each
>> instance of bash has its own separate history.  It has nothing to
>> do with your terminal emulator or your desktop environment.
> 
> Where is it if not in ~/.bash_history?

In memory.

>> Bash reads its history from a file (~/.bash_history by default) at 
>> startup time, manages it in memory while running, and writes it
>> back out to the history file upon exiting.

As Greg wrote: bash reads it in at startup time, then manages it in
memory, then writes it back out when exiting.

Unless you've configured it otherwise, the place it reads the history in
from and writes it out to is ~/.bash_history.

In between those, each and every separate instance of the shell keeps
the history in memory. Yes, if I'm not mistaken that *does* mean that if
you have 20 terminals open you have 20 copies of (some version of) the
history in memory.

> Does this separate history get written to ~/.bash_history when
> terminal emulation thing is closed?

That depends on how you have things configured. It's not really
"separate", however; it's just that history is only written out when
bash exits (sufficiently cleanly), and that's just as true when you have
multiple instances of bash as when you have only one.

-- 
   The Wanderer

The reasonable man adapts himself to the world; the unreasonable one
persists in trying to adapt the world to himself. Therefore all
progress depends on the unreasonable man. -- George Bernard Shaw



signature.asc
Description: OpenPGP digital signature


Re: bash history

2024-07-27 Thread Greg Wooledge
On Sat, Jul 27, 2024 at 23:44:08 +0100, mick.crane wrote:
> On 2024-07-27 23:08, Greg Wooledge wrote:
> > On Sat, Jul 27, 2024 at 22:50:17 +0100, mick.crane wrote:
> > > In debian bookworm, xfce desktop, different virtual terminals have a
> > > different history if same user presses "up key" in different virtual
> > > terminals ?
> > 
> > As your subject says, this is "bash history".  And yes, each instance of
> > bash has its own separate history.  It has nothing to do with your
> > terminal emulator or your desktop environment.
> Where is it if not in ~/.bash_history?

Then it's wherever you changed it to.

> > Bash reads its history from a file (~/.bash_history by default) at
> > startup time, manages it in memory while running, and writes it back
> > out to the history file upon exiting.
> 
> Does this separate history get written to ~/.bash_history when terminal
> emulation thing is closed?

You need to specify *exactly* what you're doing.

If you close a terminal emulator in such a way that it kills the shell
without letting the shell write history to disk, then the history will
not be saved.

If you want history to be saved, you should exit from the *shell*
(e.g. by pressing Ctrl-D), rather than closing the terminal and counting
on that to terminate the shell in a way that will preserve history.

If you *don't* want history to be saved, there are many ways to make
that (not) happen, depending on your terminal emulator and so on.  You'll
need to experiment, though, to see exactly what happens when you do
whatever it is you do.

Whenever I need to reboot my computer (kernel update or the like), I
decide which shells I want to retain history from, and I exit from those
cleanly (^D).  I leave the others running, and exit from FVWM, which
kills them in a way that causes their history not to be written.

If you want a particular shell window's history to be AGGRESSIVELY
written to disk every time you run a command, you can arrange for that
as well.  See <https://mywiki.wooledge.org/BashFAQ/088> for example.



Re: bash history

2024-07-27 Thread mick.crane

On 2024-07-27 23:08, Greg Wooledge wrote:

On Sat, Jul 27, 2024 at 22:50:17 +0100, mick.crane wrote:

In debian bookworm, xfce desktop, different virtual terminals have a
different history if same user presses "up key" in different virtual
terminals ?


As your subject says, this is "bash history".  And yes, each instance 
of

bash has its own separate history.  It has nothing to do with your
terminal emulator or your desktop environment.

Where is it if not in ~/.bash_history?



Bash reads its history from a file (~/.bash_history by default) at
startup time, manages it in memory while running, and writes it back
out to the history file upon exiting.


Does this separate history get written to ~/.bash_history when terminal 
emulation thing is closed?




Re: bash history

2024-07-27 Thread Andy Smith
Hi,

On Sat, Jul 27, 2024 at 10:50:17PM +0100, mick.crane wrote:
> Is this something that can be changed so history is shared between virtual
> terminals?

You may be interested in "atuin" to aggregate shell history from
multiple logins and machines in a searchable interface. It can be
self-hosted.

https://www.youtube.com/watch?v=89zPvQF3tas

Thanks,
Andy

-- 
https://bitfolk.com/ -- No-nonsense VPS hosting



Re: bash history

2024-07-27 Thread Greg Wooledge
On Sat, Jul 27, 2024 at 22:50:17 +0100, mick.crane wrote:
> In debian bookworm, xfce desktop, different virtual terminals have a
> different history if same user presses "up key" in different virtual
> terminals ?

As your subject says, this is "bash history".  And yes, each instance of
bash has its own separate history.  It has nothing to do with your
terminal emulator or your desktop environment.

Bash reads its history from a file (~/.bash_history by default) at
startup time, manages it in memory while running, and writes it back
out to the history file upon exiting.

> Is this something that can be changed so history is shared between virtual
> terminals?

No.

I consider this a *good* thing, personally.  I used commerical Unix with
ksh for a very long time, and ksh shares history between instances in
real time.  This is a *nightmare*.  I really, really disliked it.

In the worst case scenario, you and a coworker might both be logged in
as root (where root's shell is ksh) simultaneously.  Your histories
would then intermix in real time.  You might press ESC k ENTER in your
terminal, expecting to re-run the command you had just executed a
moment ago, and unexpectedly run your coworker's command.

Even in a "normal" scenario where I'm logged in as myself, and nobody
else has my password, I would not want all of my terminal windows to have
a shared history.  Each of them is doing something different.  I want
each terminal's workflow to be isolated to that terminal and what I'm
doing in it.  I don't want them contaminating each other.

Of course, that's my opinion, and if you want a shared history across
concurrent shell instances, there are probably shells that can do that.
I've never looked for it, because having lived with it, I already know
I don't want it again.



bash history

2024-07-27 Thread mick.crane
In debian bookworm, xfce desktop, different virtual terminals have a 
different history if same user presses "up key" in different virtual 
terminals ?
Is this something that can be changed so history is shared between 
virtual terminals?

mick



Re: Maybe off topic: Where is bash gesture ${X=Y} described ?

2024-07-24 Thread Max Nikulin

On 24/07/2024 20:50, Greg Wooledge wrote:

Everyone skips over the sentence that begins with "Omitting the colon".

Every time we try to tell Chet, "Hey, man, please add examples that
show BOTH syntaxes", he blows us off, because this is the way POSIX
documents it.  If it's good enough for POSIX, then it must be good
enough for bash, right?[1]


For a long time I was believing that ${X=Y} is just an obsolete and less 
strict form of ${X:=Y} due to the way it is documented in BASH. Once I 
needed to distinguish empty an unset values. First hits in search engine 
results gave me impression that people just did not care. Fortunately I 
spotted <https://stackoverflow.com/a/16753536> with both variants (a 
quote from POSIX). I agree that colon vs. no colon should be documented 
in a more prominent way.




Re: Maybe off topic: Where is bash gesture ${X=Y} described ?

2024-07-24 Thread tomas
On Wed, Jul 24, 2024 at 09:50:36AM -0400, Greg Wooledge wrote:

[...]

> Everyone skips over the sentence that begins with "Omitting the colon".

Thanks for this one. I know /I/ did for long enough.

Greg, this place would be a lot less helpful...

> Every time we try to tell Chet, "Hey, man, please add examples that
> show BOTH syntaxes" [...]

...and definitely more boring without you. Thanks for that :-)

Cheers
-- 
t


signature.asc
Description: PGP signature


Re: Maybe off topic: Where is bash gesture ${X=Y} described ?

2024-07-24 Thread Thomas Schmitt
Hi,

i wrote:
> > maybe i am just too dumb to read the manual, or maybe i made an
> > archeological discovery in the shells we use.

Greg Wooledge wrote:
> Everyone skips over the sentence that begins with "Omitting the colon".

Oh well. Too dumb and not alone.

I did read the sentence immediately before "Omitting the colon".

In man dash the statement comes after the list of modifications:

  In the parameter expansions shown previously, use of the colon in the
  format results in a test for a parameter that is unset or null; omission
  of the colon results in a test for a parameter that is only unset.

If there would be written ":" instead of "colon" i might have passed the
brain agility test.


Have a nice day :)

Thomas



Re: Maybe off topic: Where is bash gesture ${X=Y} described ?

2024-07-24 Thread Greg Wooledge
On Wed, Jul 24, 2024 at 15:33:11 +0200, Thomas Schmitt wrote:
> GRUB's test scripts often show this gesture
> 
>   : "${TMPDIR=/tmp}"
> 
> Well known and described is
>   ${X:=Y}
> which assigns a default value to variable X if it is empty (man bash
> says: "If [...] unset or null").
> Also known and described is ":", the no-op command.
> So
>   : "${TMPDIR:=/tmp}"
> would not be a riddle. But "=" instead ":=" causes a subtle change in
> behavior. A defined but empty variable does not get the default content:


$ man bash
[...]
   Parameter Expansion
   [...]
   When not performing substring expansion, using the forms documented be‐
   low  (e.g.,  :-),  bash  tests  for  a parameter that is unset or null.
   Omitting the colon results in a test only for a parameter that  is  un‐
   set.

   ${parameter:-word}
  Use  Default  Values. [...]


Everyone skips over the sentence that begins with "Omitting the colon".

Every time we try to tell Chet, "Hey, man, please add examples that
show BOTH syntaxes", he blows us off, because this is the way POSIX
documents it.  If it's good enough for POSIX, then it must be good
enough for bash, right?[1]

Ordinary users search for the SYNTAX.  Then when they find a list of
examples, they only read that list.  They don't read the text BEFORE
the list.  They might read text AFTER the list, but even that's rare.

This is why I created <https://mywiki.wooledge.org/BashSyntaxReference>.
You can look up syntax there and see what it does.


[1]Hmm, it looks like POSIX added a table:
   
<https://pubs.opengroup.org/onlinepubs/9799919799/utilities/V3_chap02.html#tag_19_06_02>
   actually shows both forms, if you scroll down a bit.



Maybe off topic: Where is bash gesture ${X=Y} described ?

2024-07-24 Thread Thomas Schmitt
Hi,

maybe i am just too dumb to read the manual, or maybe i made an
archeological discovery in the shells we use.

I came to a strange shell gesture which i find neither in man bash nor
man dash. Nevertheless it works the same in both shells.

GRUB's test scripts often show this gesture

  : "${TMPDIR=/tmp}"

Well known and described is
  ${X:=Y}
which assigns a default value to variable X if it is empty (man bash
says: "If [...] unset or null").
Also known and described is ":", the no-op command.
So
  : "${TMPDIR:=/tmp}"
would not be a riddle. But "=" instead ":=" causes a subtle change in
behavior. A defined but empty variable does not get the default content:

  $ unset x
  $ : ${x=YYY}
  $ echo $x
  YYY
  $ x=
  $ : ${x=YYY}
  $ echo $x

  $

With ":=" the empty variable gets a new stuffing:

  $ : ${x:=YYY}
  $ echo $x
  YYY
  $

The dash shell instead of bash shows the same behavior.

Is this legacy behavior ?
Are there shells which do ${X=Y} but not ${X:=Y} ?


Reason why i ask:

I came to that gesture while trying to find out why a run of GRUB's
"make check" as superuser left a lot of empty directories in the
/-directory, Most GRUB tests do early

  : "${TMPDIR=/tmp}"

or use variable expansion with default value: ${TMPDIR:-/tmp}
But tests/grub_cmd_cryptomount uses TMPDIR naively so that its test
directories end up as
  /1718898505.LUKS1_test_cryptsetup_defaults
  ...
  
/1718912880.LUKS2_test_with_second_key_slot_and_first_slot_using_different_password

I would like to talk GRUB into using ${X:=Y} generally, because it does
not matter whether TMPDIR is defined empty or is unset.
So i need background knowledge about the currently used ${X=Y}.

(One may say that is not a good idea to run a test as superuser.
But most GRUB tests create and mount filesystems. So after a change in
the tool grub-fstest i had to do it as superuser to check for new test
failures caused by my change. It was only one and that was expected.)


Have a nice day :)

Thomas



[SOLVED] Re: variables in bash

2024-03-28 Thread Hans
Hi, 

thank you all for the fast response. It helped a lot and made everything 
clear.

The problem is solved.

Have a nice eastern.

Best

Hans







Re: variables in bash

2024-03-28 Thread Paul M Foster
On Thu, Mar 28, 2024 at 10:37:25AM +0100, Hans wrote:

> Hi folks,
> 
> just an easy question:
> 
> What is the difference (if any) between the following two variables in a 
> shellfile in bash:
> 
> 1. mypath=/home/user1/Tools/

Here you are assigning a value to the variable "mypath". You can surround
"/home/user1/Tools" with quotes if you like, but it is not strictly
necessary.

> 
> and $mypath

Here you are actually *using* the variable "mypath".

Here is another example:

NAME="paulf"
echo "My name is $NAME."

which will yield:

My name is paulf.


-- 
Paul M. Foster
Personal Blog: http://noferblatz.com
Company Site: http://quillandmouse.com
Software Projects: https://gitlab.com/paulmfoster



Re: variables in bash

2024-03-28 Thread Greg Wooledge
On Thu, Mar 28, 2024 at 10:37:25AM +0100, Hans wrote:
> What is the difference (if any) between the following two variables in a 
> shellfile in bash:
> 
> 1. mypath=/home/user1/Tools/
> 2. mypath="/home/user1/Tools/"

They are the same.  The quotes are optional here, because your assignment
doesn't contain any whitespace.

The quotes would be required if you had something like:

mypath="/mnt/c/Program Files/"

In any case, the assignment is the easy part.  Most people get this
part right.  Where they screw up is here:

> and $mypath

Whenever[1] you use "$mypath", you'll want double quotes around it.
Otherwise, it'll get split into multiple words at whitespace, and
will also be subject to filename expansion.  You don't want that.

mypath="/mnt/c/Program Files/"
if ! test -d $mypath; then ...  # wrong

The example above will *not* work, because the space in the middle
of $mypath's value will cause the test command to receive two
separate words, instead of one word.  It needs to be quoted:

mypath="/mnt/c/Program Files/"
if ! test -d "$mypath"; then ...# right

> Is this in bash the same? Do other shells (sh, zsh, whatever) handle these 
> two 
> different?

Most quoting rules are the same in all sh-derived shells, including the
rules I talked about here.

As you dive deeper into shell scripting, you'll find some cases where
the rules change a bit across different shells, but so far you're still
in the shallow end.

[1] There are some exceptions, but for now, go with the simplest rule:
"When in doubt, double-quote it."



variables in bash

2024-03-28 Thread Hans
Hi folks,

just an easy question:

What is the difference (if any) between the following two variables in a 
shellfile in bash:

1. mypath=/home/user1/Tools/

and $mypath

or
2. mypath="/home/user1/Tools/"

and $mypath

Is this in bash the same? Do other shells (sh, zsh, whatever) handle these two 
different?

Thanks for any answer, can be short!

Best regards

Hans


  




Re: bash parameter expansion "doesn't like" dots?

2024-03-05 Thread Max Nikulin

On Tue, 5 Mar 2024 at 02:59, Greg Wooledge wrote:


We might *guess* that this change was made to make dash more strict
about POSIX minimalism (removing extensions), but without documentation
we can't do more than guess about motives.


The motivation is to avoid difference in behavior when compiled with 
internal fnmatch implementation and with glibc


https://lore.kernel.org/dash/e341e41f-8c32-b6e4-8be3-8f94fae26...@gigawatt.nl/
Re: possible wrong behaviour with patterns using a quoted ^ at the start 
of a bracket expression. Wed, 12 Jan 2022 17:20:54 +
This bug (you're right that it's a bug) is specific to builds that use 
fnmatch(). In dash itself, ^ is always assumed as a literal. In builds 
with --disable-fnmatch you get correct results.


On 05/03/2024 12:22, David wrote:

A bit more info:
   https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=1028002


Unfortunately this bug has been left without a response from the 
maintainer. The release notes mentions the issue:


https://www.debian.org/releases/bookworm/amd64/release-notes/ch-information.en.html#dash-circumflex
https://bugs.debian.org/1034344




Re: bash parameter expansion "doesn't like" dots?

2024-03-04 Thread David
On Tue, 5 Mar 2024 at 02:59, Greg Wooledge  wrote:
> On Tue, Mar 05, 2024 at 11:24:11AM +0900, John Crawley wrote:

> > ^ worked as a negator in dash character classes up to Bullseye though, so 
> > something has changed recently. That's what my web searching failed to 
> > find...
>
> It looks like dash doesn't have up-to-date documentation on its changes.
> There's a ChangeLog file in the upstream Git repository's top level
> directory[1] (shipped as changelog.gz in the Debian package), but the most
> recent entry in it is dated 2014-11-17.
>
> We might *guess* that this change was made to make dash more strict
> about POSIX minimalism (removing extensions), but without documentation
> we can't do more than guess about motives.
>
> [1] https://git.kernel.org/pub/scm/utils/dash/dash.git/tree/

A bit more info:
  https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=1028002

Previous discussion on debian-user:
  https://lists.debian.org/debian-user/2023/04/msg00559.html



Re: bash parameter expansion "doesn't like" dots?

2024-03-04 Thread Greg Wooledge
On Tue, Mar 05, 2024 at 11:24:11AM +0900, John Crawley wrote:
> ^ worked as a negator in dash character classes up to Bullseye though, so 
> something has changed recently. That's what my web searching failed to find...

It looks like dash doesn't have up-to-date documentation on its changes.
There's a ChangeLog file in the upstream Git repository's top level
directory[1] (shipped as changelog.gz in the Debian package), but the most
recent entry in it is dated 2014-11-17.

We might *guess* that this change was made to make dash more strict
about POSIX minimalism (removing extensions), but without documentation
we can't do more than guess about motives.

[1] https://git.kernel.org/pub/scm/utils/dash/dash.git/tree/



Re: bash parameter expansion "doesn't like" dots?

2024-03-04 Thread John Crawley

On 05/03/2024 11:36, Max Nikulin wrote:

On 05/03/2024 09:02, Greg Wooledge wrote:

On Tue, Mar 05, 2024 at 10:49:34AM +0900, John Crawley wrote:


I think ^ has been deprecated recently. I failed to find a reference on the web 
just now though.


So, ^ isn't "deprecated".  It's just not portable to sh.


Running shellcheck on a *sh* script with a [^s] glob gives 
https://www.shellcheck.net/wiki/SC3026
"In POSIX sh, ^ in place of ! in glob bracket expressions is undefined."
with some links. There is no warning in the case of a #!/bin/bash script.



Thanks! Shellcheck also says:
"Dash used to support [^c] when compiled with fnmatch and glob from glibc, but it 
was considered as a bug and fixed in version 0.5.12."

That's the version of dash which arrived in Debian Bookworm.
--
John



Re: bash parameter expansion "doesn't like" dots?

2024-03-04 Thread Max Nikulin

On 05/03/2024 09:02, Greg Wooledge wrote:

On Tue, Mar 05, 2024 at 10:49:34AM +0900, John Crawley wrote:


I think ^ has been deprecated recently. I failed to find a reference on the web 
just now though.


So, ^ isn't "deprecated".  It's just not portable to sh.


Running shellcheck on a *sh* script with a [^s] glob gives 
https://www.shellcheck.net/wiki/SC3026

"In POSIX sh, ^ in place of ! in glob bracket expressions is undefined."
with some links. There is no warning in the case of a #!/bin/bash script.




Re: bash parameter expansion "doesn't like" dots?

2024-03-04 Thread John Crawley

On 05/03/2024 11:02, Greg Wooledge wrote:

On Tue, Mar 05, 2024 at 10:49:34AM +0900, John Crawley wrote:

On 05/03/2024 05:27, David Wright wrote:

Which shell also matters. The OP appears to be using ^ to negate,
but ! has the advantage that it will be understood in bash and dash.


I think ^ has been deprecated recently. I failed to find a reference on the web 
just now though.


POSIX specifies that ! is the negation character in glob ranges, largely
because ^ used to be a synonym for | in the old Bourne shell (for the
benefit of keyboards that didn't have a convenient | character).

The use of ^ as a glob negation is a bash extension.  It's nice for
people who may not even realize that they're supposed to be using !
because they learned regular expressions first.

So, ^ isn't "deprecated".  It's just not portable to sh.


^ worked as a negator in dash character classes up to Bullseye though, so 
something has changed recently. That's what my web searching failed to find...

--
John



Re: bash parameter expansion "doesn't like" dots?

2024-03-04 Thread Greg Wooledge
On Tue, Mar 05, 2024 at 10:49:34AM +0900, John Crawley wrote:
> On 05/03/2024 05:27, David Wright wrote:
> > Which shell also matters. The OP appears to be using ^ to negate,
> > but ! has the advantage that it will be understood in bash and dash.
> 
> I think ^ has been deprecated recently. I failed to find a reference on the 
> web just now though.

POSIX specifies that ! is the negation character in glob ranges, largely
because ^ used to be a synonym for | in the old Bourne shell (for the
benefit of keyboards that didn't have a convenient | character).

The use of ^ as a glob negation is a bash extension.  It's nice for
people who may not even realize that they're supposed to be using !
because they learned regular expressions first.

So, ^ isn't "deprecated".  It's just not portable to sh.



Re: bash parameter expansion "doesn't like" dots?

2024-03-04 Thread John Crawley

On 05/03/2024 05:27, David Wright wrote:

Pattern matching in the shell is not the same as in grep: the
rules are different, but similar enough to confuse.

Grep uses regular expressions, while the shell is usually globs. (I have no 
experience of shells other than dash and bash though.)
Bash can compare with regexes using the =~ operator [[ $A =~ $B ]] ...


Which shell also matters. The OP appears to be using ^ to negate,
but ! has the advantage that it will be understood in bash and dash.


I think ^ has been deprecated recently. I failed to find a reference on the web 
just now though.

Testing with dash on Bullseye:
$ v=string
$ echo ${v#*[!s]}
ring
$ echo ${v#*[^s]}
ring

But on Bookworm:
$ v=string
$ echo ${v#*[!s]}
ring
$ echo ${v#*[^s]}
tring

Now the ^ is being treated as just a list member.

With Bash the ^ still seems to be treated as a negator on Bookworm.

So yes, we should be switching to !

--
John



Re: bash parameter expansion "doesn't like" dots?

2024-03-04 Thread David Wright
On Mon 04 Mar 2024 at 11:51:29 (+0900), John Crawley wrote:
> On 04/03/2024 10:07, David Wright wrote:
> > On Sun 03 Mar 2024 at 17:58:53 (-0600), Albretch Mueller wrote:
> > >   bash doesn't seem to like dots too close to brackets:
> > > 
> > >   echo "${_VAR//[^0-9a-zA-Z.,_-]/}"
> > > 
> > >   works fine.
> > > 
> > > On 3/3/24, Albretch Mueller  wrote:
> > > > _VAR="admissions.piedmont.edu_files?trackid=wnm:1980=what-is-the-second-fundamental-theorem-of-calculus(1).pdf"
> > > > 
> > > > echo "${_VAR//[^a-zA-Z0-9_-]/}"
> > > > 
> > > > echo "${_VAR//[^a-zA-Z0-9_-.]/}"
> >   ↑↑↑
> > 
> > That's a range, except that it isn't because it's written backwards.
> > Check for yourself by testing with 9-0 instead of 0-9.
> > 
> So the problem isn't about dots,

It shouldn't be, as there's nothing special about ".", though there's
the mystery of what was said in the OP's quoted post, which we're not
privy to.

> but the handling of the - which has to go last if it isn't to be treated as a 
> range marker.

First or last in the set. I prefer last, because "]" can only go first
in the set to be a matchable character.

> https://www.gnu.org/software/grep/manual/html_node/Character-Classes-and-Bracket-Expressions.html
> says:
> 
> ‘-’
> represents the range if it’s not first or last in a list or the ending 
> point of a range. To make the ‘-’ a list item, it is best to put it last.

Well, here's a clue as to where the trouble might have arisen.
Pattern matching in the shell is not the same as in grep: the
rules are different, but similar enough to confuse.

Which shell also matters. The OP appears to be using ^ to negate,
but ! has the advantage that it will be understood in bash and dash.

Cheers,
David.



Re: bash parameter expansion "doesn't like" dots?

2024-03-03 Thread John Crawley

On 04/03/2024 10:07, David Wright wrote:

On Sun 03 Mar 2024 at 17:58:53 (-0600), Albretch Mueller wrote:

  bash doesn't seem to like dots too close to brackets:

  echo "${_VAR//[^0-9a-zA-Z.,_-]/}"

  works fine.

On 3/3/24, Albretch Mueller  wrote:

_VAR="admissions.piedmont.edu_files?trackid=wnm:1980=what-is-the-second-fundamental-theorem-of-calculus(1).pdf"

echo "${_VAR//[^a-zA-Z0-9_-]/}"

echo "${_VAR//[^a-zA-Z0-9_-.]/}"

  ↑↑↑

That's a range, except that it isn't because it's written backwards.
Check for yourself by testing with 9-0 instead of 0-9.

Cheers,
David.


So the problem isn't about dots, but the handling of the - which has to go last 
if it isn't to be treated as a range marker.

https://www.gnu.org/software/grep/manual/html_node/Character-Classes-and-Bracket-Expressions.html
says:

‘-’
represents the range if it’s not first or last in a list or the ending 
point of a range. To make the ‘-’ a list item, it is best to put it last.

--
John



Re: bash parameter expansion "doesn't like" dots?

2024-03-03 Thread David Wright
On Sun 03 Mar 2024 at 17:58:53 (-0600), Albretch Mueller wrote:
>  bash doesn't seem to like dots too close to brackets:
> 
>  echo "${_VAR//[^0-9a-zA-Z.,_-]/}"
> 
>  works fine.
> 
> On 3/3/24, Albretch Mueller  wrote:
> > _VAR="admissions.piedmont.edu_files?trackid=wnm:1980=what-is-the-second-fundamental-theorem-of-calculus(1).pdf"
> >
> > echo "${_VAR//[^a-zA-Z0-9_-]/}"
> >
> > echo "${_VAR//[^a-zA-Z0-9_-.]/}"
 ↑↑↑

That's a range, except that it isn't because it's written backwards.
Check for yourself by testing with 9-0 instead of 0-9.

Cheers,
David.



Re: bash parameter expansion "doesn't like" dots?

2024-03-03 Thread Albretch Mueller
 bash doesn't seem to like dots too close to brackets:

 echo "${_VAR//[^0-9a-zA-Z.,_-]/}"

 works fine.

 lbrtchx

On 3/3/24, Albretch Mueller  wrote:
> _VAR="admissions.piedmont.edu_files?trackid=wnm:1980=what-is-the-second-fundamental-theorem-of-calculus(1).pdf"
>
> echo "${_VAR//[^a-zA-Z0-9_-]/}"
>
> echo "${_VAR//[^a-zA-Z0-9_-.]/}"
>



[HS] assistance au code (Re: Script BASH gestion des espaces des noms de fichier)

2024-02-05 Thread Sébastien NOBILI

Bonjour,

Le 2024-02-05 16:07, Daniel Caillibaud a écrit :
Oui, et je vous encourage à passer vos shell bash à shellcheck, il 
signale ce genre d'erreur

(et plein d'autres).
Il est parfois un peut trop zélé, mais on peut lui dire qu'on sait ce 
qu'on fait avec du


  # shellcheck disable=SC

avant la ligne qui le fait râler (où  est le code d'erreur qu'il 
signale)


Avec Neovim, on peut avoir ce genre d'assistance en direct :)

Sébastien



Re: Script BASH gestion des espaces des noms de fichier

2024-02-05 Thread Daniel Caillibaud
Le 02/02/24 à 08:54, Jérémy Prego  a écrit :
> Pour éviter ce problème, on peut mettre les variables entre "
> 
> du coup, ça donnerai:
> 
> pdftk "$fichier1" stamp "$tampon" output "$fichier2"

Oui, et je vous encourage à passer vos shell bash à shellcheck, il signale ce 
genre d'erreur
(et plein d'autres).
Il est parfois un peut trop zélé, mais on peut lui dire qu'on sait ce qu'on 
fait avec du

  # shellcheck disable=SC

avant la ligne qui le fait râler (où  est le code d'erreur qu'il signale)

-- 
Daniel

La pensée vole et les mots vont à pied. Voilà tout le drame de l'écrivain.
Julien Green



Re: Script BASH gestion des espaces des noms de fichier

2024-02-02 Thread Pierre Malard
Essaie des cotes dans tes attributions de noms.

Par exemple :
TOTO="${NomFic}"

avec
NomFic="Mon Fichier"

Pareillement cote les appels :
Cmd —variable "${NomFic}"

Par exemple. Le fait de coter l’appel de variable avec des double cote permet à 
BASH de considérer NomFic comme un seul paramètre envoyé à Cmd avec ses blancs. 
Après il faut savoir comment la commande Cmd va traiter tout ça…

> Le 2 févr. 2024 à 07:51, Informatique BILLARD 
>  a écrit :
> 
> Bonjour
> 
> j'ai écrit un petit script qui lance à la fin cette commande :
> 
> pdftk $fichier1 stamp $tampon output $fichier2
> 
> avec $fichier1 et $tampon, $fichier2  sont construit à partir des paramètres 
> fournis au script .
> 
> Mais je rencontre un problème quand il y a un espace dans le nom de fichier 
> ou le répertoire pour pdftk ces espaces engendrent une erreur.
> 
> J'ai pourtant placé l'antislah avant mes espace dans l'affectation des 
> variables.
> 
> tampon=/user/Document/cachet\ pdf
> 
> Merci par avance
> 
> François-Marie
> 

--
Pierre Malard
Responsable architectures système CDS DINAMIS/THEIA Montpellier
IRD - UMR Espace-Dev - UAR CPST - IR Data-Terra
Maison de la Télédétection
500 rue Jean-François Breton
34093 Montpellier Cx 5
France

   « SPAM : Spieced Pork and Meat »
   Pierre Dac (Londres, 1944)
Extrait de « Pierre DAC parle au Français » sur Radio Londres, le 24 mars 1944, 
dans Drôle de guerre, éditions Omnibus (2008), pages 93 à 96. 
(https://www.epi.asso.fr/revue/articles/a1602d.htm)

   |\  _,,,---,,_
   /,`.-'`'-.  ;-;;,_
  |,4-  ) )-,_. ,\ (  `'-'
 '---''(_/--'  `-'\_)   πr

perl -e '$_=q#: 3|\ 5_,3-3,2_: 3/,`.'"'"'`'"'"' 5-.  ;-;;,_:  |,A-  ) )-,_. ,\ 
(  `'"'"'-'"'"': '"'"'-3'"'"'2(_/--'"'"'  `-'"'"'\_): 
24πr::#;y#:#\n#;s#(\D)(\d+)#$1x$2#ge;print'
- --> Ce message n’engage que son auteur <--



signature.asc
Description: Message signed with OpenPGP


Re: Script BASH gestion des espaces des noms de fichier

2024-02-02 Thread Erwann Le Bras

Effectivement François

Merci d'avoir rectifié.

Erwann

Le 02/02/2024 à 13:09, François TOURDE a écrit :

Le 19755ième jour après Epoch,
Erwann Le Bras écrivait:


Éviter les boucles "for" avec listes de fichiers (for f in `ls
"$dir"`) ou (for f in *), les espaces sont mal interprétés.

Ça marche très bien l'utilisation avec for f in *, si tu prends soin
d'utiliser "$f" plutôt que juste $f

Par contre, le "in `ls *`" n'est effectivement pas une bonne idée.


Re: Script BASH gestion des espaces des noms de fichier

2024-02-02 Thread François TOURDE
Le 19755ième jour après Epoch,
Erwann Le Bras écrivait:

> Éviter les boucles "for" avec listes de fichiers (for f in `ls
> "$dir"`) ou (for f in *), les espaces sont mal interprétés.

Ça marche très bien l'utilisation avec for f in *, si tu prends soin
d'utiliser "$f" plutôt que juste $f

Par contre, le "in `ls *`" n'est effectivement pas une bonne idée.



Re: Script BASH gestion des espaces des noms de fichier

2024-02-02 Thread Erwann Le Bras

bonjour

comme dis par ailleurs, pas de problème avec les espaces si les 
variables et chemins sont bien protégés  avec des doubles-cotes (["])


fichier="mon fichier"
dir="$HOME/mon répertoire"
cp "$fichier" "$dir"

Éviter les boucles "for" avec listes de fichiers (for f in `ls "$dir"`) 
ou (for f in *), les espaces sont mal interprétés.

À la place utiliser "find" : find "$dir" -name "${fichier}*" -exec

c'est à peu près tout.

Erwann

Le 02/02/2024 à 08:41, Informatique BILLARD a écrit :


Bonjour

j'ai écrit un petit script qui lance à la fin cette commande :

pdftk $fichier1 stamp $tampon output $fichier2

avec $fichier1 et $tampon, $fichier2  sont construit à partir des 
paramètres fournis au script .


Mais je rencontre un problème quand il y a un espace dans le nom de 
fichier ou le répertoire pour pdftk ces espaces engendrent une erreur.


J'ai pourtant placé l’antislash avant mes espace dans l'affectation 
des variables.


tampon=/user/Document/cachet*\ *pdf

Merci par avance

François-Marie


Re: Script BASH gestion des espaces des noms de fichier

2024-02-02 Thread Informatique BILLARD

merci je ne connaissais pas cet outils

François-Marie

Le 02/02/2024 à 09:54, Klaus Becker a écrit :

Detox est ton ami

Klaus

Re: Script BASH gestion des espaces des noms de fichier

2024-02-02 Thread Informatique BILLARD

Bon

j'ai tourné le problème dans tous les sens et finalement j'ai opté pour 
ceci


1. le nom du fichier passé comme argument au script est traité pour
   remplacer les espaces par des underscore.
2. je fait un renommage de ce fichier avec le nom sans espaces.
3. Puis traitement et tout fonctionne.

Merci à vous.

François-Marie


Le 02/02/2024 à 08:57, Cyrille a écrit :

Bjr,


tampon=/user/Document/cachet\ pdf

et
tampon="/user/Document/cachet\ pdf"
(utiliser des double quote

??

++


Re: Script BASH gestion des espaces des noms de fichier

2024-02-02 Thread Klaus Becker
Detox est ton ami

Klaus


Re: Script BASH gestion des espaces des noms de fichier

2024-02-02 Thread Informatique BILLARD

Le 02/02/2024 à 08:48, Basile Starynkevitch a écrit :


On 2/2/24 08:41, Informatique BILLARD wrote:


Bonjour

j'ai écrit un petit script qui lance à la fin cette commande :

pdftk $fichier1 stamp $tampon output $fichier2

avec $fichier1 et $tampon, $fichier2  sont construit à partir des 
paramètres fournis au script .


Mais je rencontre un problème quand il y a un espace dans le nom de 
fichier ou le répertoire pour pdftk ces espaces engendrent une erreur.


J'ai pourtant placé l’antislash avant mes espace dans l'affectation 
des variables.


tampon=/user/Document/cachet*\ *pdf

Une solution simple c'est de s'interdire les espaces dans les noms de 
fichiers. Pourquoi ne pas coder par exemple
Oui en effet j'ai fini par supprimer les espaces dans les noms de 
fichiers et répertoires. Cependant ce script traite des fichiers 
ayant parfois des espaces et si je dois renommer à chaque fois je 
vais perdre l'intérêt du script.



tampon=/user/Document/cachet.pdf

et ensuite lancer votre script avec /bin/bash -vx lescriptbash


Merci par avance

François-Marie





Script BASH gestion des espaces des noms de fichier

2024-02-02 Thread Informatique BILLARD

Bonjour

j'ai écrit un petit script qui lance à la fin cette commande :

pdftk $fichier1 stamp $tampon output $fichier2

avec $fichier1 et $tampon, $fichier2  sont construit à partir des 
paramètres fournis au script .


Mais je rencontre un problème quand il y a un espace dans le nom de 
fichier ou le répertoire pour pdftk ces espaces engendrent une erreur.


J'ai pourtant placé l'antislah avant mes espace dans l'affectation des 
variables.


tampon=/user/Document/cachet*\ *pdf

Merci par avance

François-Marie


Re: Script BASH gestion des espaces des noms de fichier

2024-02-02 Thread Cyrille
Bjr,

> tampon=/user/Document/cachet\ pdf
et 
tampon="/user/Document/cachet\ pdf"
(utiliser des double quote

??

++



Re: Script BASH gestion des espaces des noms de fichier

2024-02-01 Thread Jérémy Prego

bonjour,

Le 02/02/2024 à 08:41, Informatique BILLARD a écrit :


Bonjour

j'ai écrit un petit script qui lance à la fin cette commande :

pdftk $fichier1 stamp $tampon output $fichier2



Pour éviter ce problème, on peut mettre les variables entre "

du coup, ça donnerai:

pdftk "$fichier1" stamp "$tampon" output "$fichier2"

avec $fichier1 et $tampon, $fichier2  sont construit à partir des 
paramètres fournis au script .


Mais je rencontre un problème quand il y a un espace dans le nom de 
fichier ou le répertoire pour pdftk ces espaces engendrent une erreur.


J'ai pourtant placé l’antislash avant mes espace dans l'affectation 
des variables.


tampon=/user/Document/cachet*\ *pdf

Merci par avance

François-Marie



Jerem

Re: Script BASH gestion des espaces des noms de fichier

2024-02-01 Thread Basile Starynkevitch



On 2/2/24 08:41, Informatique BILLARD wrote:


Bonjour

j'ai écrit un petit script qui lance à la fin cette commande :

pdftk $fichier1 stamp $tampon output $fichier2

avec $fichier1 et $tampon, $fichier2  sont construit à partir des 
paramètres fournis au script .


Mais je rencontre un problème quand il y a un espace dans le nom de 
fichier ou le répertoire pour pdftk ces espaces engendrent une erreur.


J'ai pourtant placé l’antislash avant mes espace dans l'affectation 
des variables.


tampon=/user/Document/cachet*\ *pdf

Une solution simple c'est de s'interdire les espaces dans les noms de 
fichiers. Pourquoi ne pas coder par exemple


tampon=/user/Document/cachet.pdf

et ensuite lancer votre script avec /bin/bash -vx lescriptbash


Merci par avance

François-Marie


--
Basile Starynkevitch 
(only mine opinions / les opinions sont miennes uniquement)
92340 Bourg-la-Reine, France
web page: starynkevitch.net/Basile/
See/voir:   https://github.com/RefPerSys/RefPerSys



Script BASH gestion des espaces des noms de fichier

2024-02-01 Thread Informatique BILLARD

Bonjour

j'ai écrit un petit script qui lance à la fin cette commande :

pdftk $fichier1 stamp $tampon output $fichier2

avec $fichier1 et $tampon, $fichier2  sont construit à partir des 
paramètres fournis au script .


Mais je rencontre un problème quand il y a un espace dans le nom de 
fichier ou le répertoire pour pdftk ces espaces engendrent une erreur.


J'ai pourtant placé l’antislash avant mes espace dans l'affectation des 
variables.


tampon=/user/Document/cachet*\ *pdf

Merci par avance

François-Marie


Re: exemple en GNU bash de variable tableau

2024-01-29 Thread Étienne Mollier
Bonsoir Basile,

Basile Starynkevitch, on 2024-01-29:
> J'essaie de collecter dans une variable tableau de bash  files_to_remove les
> fichiers temporaires (qu'il faudrait suprimer à la fin de cez script).
> 
> Je n'arrive pas à comprendre la syntaxe des variables tableau en GNU bash.

Comme le veut l'adage, un exemple clair vaut mieux que des
mégaoctets de documentation.  Pour initialiser les entrées d'un
tableau, on peut faire comme ceci :

$ TAB[0]='zero'
$ TAB[1]='un'
$ TAB[2]='deux'

Et pour accéder aux valeurs, il faut impérativement entourer la
variable avec l'index d'accolades, comme suit :

$ echo "${TAB[0]}"
zero
$ echo "${TAB[1]}"
un
$ echo "${TAB[2]}"
deux

Il y a deux méthodes bien distinctes pour accéder à tous les
éléments d'un coup, via l'astérisque ou l'arobaze, illustrées
par l'exemple ci-dessous :

$ for elem in "${TAB[*]}"; do echo "  * $elem"; done
  * zero un deux
$ for elem in "${TAB[@]}"; do echo "  * $elem"; done
  * zero
  * un
  * deux

À noter que dans ce genre de situations, il devient essentiel
d'être clair sur l'usage systématique des double quotes.

Une construction courante pour accéder aux éléments à partir de
l'index, comme celà arrive fréquemment en langages compilés
impératifs, peut ressembler à ça :

$ for i in $(seq 0 2) ; do echo " $i. ${TAB[$i]}"; done
 0. zero
 1. un
 2. deux

Il est aussi possible de construire et de concaténer des
tableaux avec l'opérateur "parenthèse", par exemple :

$ TAB=( "${TAB[@]}" "trois" "quatre" )
$ for elem in "${TAB[@]}"; do echo "  * $elem"; done
  * zero
  * un
  * deux
  * trois
  * quatre

Là encore, l'usage de l'arobase et des double quotes est
essentiel pour que la concaténation se passe comme attendu :

$ TAB_SUITE=( "le cinquieme" "le sixieme" )
$ TAB_INATTENDU=( "${TAB[*]}" ${TAB_SUITE[@]} )
$ for elem in "${TAB_INATTENDU[@]}" ; do echo "  * $elem" ; done
  * zero un deux trois quatre
  * le
  * cinquieme
  * le
  * sixieme
$ TAB_ATTENDU=( "${TAB[@]}" "${TAB_SUITE[@]}" )
$ for elem in "${TAB_ATTENDU[@]}" ; do echo "  * $elem" ; done
  * zero
  * un
  * deux
  * trois
  * quatre
  * le cinquieme
  * le sixieme

La documentation de référence sur les tableaux du bash se trouve
dans le manuel de bash(1) au chapitre "Array", qui peut être
retrouvé en effectuant une recherche de l'expression rationnelle
"^ Arrays".

Bonne soirée,  :)
-- 
  .''`.  Étienne Mollier 
 : :' :  pgp: 8f91 b227 c7d6 f2b1 948c  8236 793c f67e 8f0d 11da
 `. `'   sent from /dev/pts/5, please excuse my verbosity
   `-on air: Life Line Project - Unica


signature.asc
Description: PGP signature


Re: exemple en GNU bash de variable tableau

2024-01-29 Thread Basile Starynkevitch



On 1/29/24 16:48, Michel Verdier wrote:

Le 29 janvier 2024 Basile Starynkevitch a écrit :


J'essaie de collecter dans une variable tableau de bash  files_to_remove les
fichiers temporaires (qu'il faudrait suprimer à la fin de cez script).

Pourquoi un tableau ? Une simple liste ne suffit pas ?



Bien sûr que si, pour le script 
https://github.com/RefPerSys/RefPerSys/blob/master/do-configure-refpersys.bash


(le script de configuration du moteur d'inférences libre RefPerSys en 
http://refpersys.org/ )


*Une liste simplement chainée mais _mutable_ conviendrait tout à fait.*


La question plus technique devient: *comment implémente-t-on* (en 
quelques lignes de GNU bash sous Linux) *une telle liste simplement 
chainée*.



Pour rappel: C++ a des listes simplement chainées (pour les détails 
consulter https://en.cppreference.com/w/cpp/container/list ...)


et Ocaml a des listes simplement chainées (pour les détails consulter 
https://v2.ocaml.org/api/List.html )


et Guile ou Scheme a des listes simplement chainées (voir la section 
6.3.2 du R5RS 
<https://conservatory.scheme.org/schemers/Documents/Standards/R5RS/HTML/>)



Un exemple en GNU bash (testable sous Linux) de liste simplement chainée 
me convient.


L'exemple 
https://www.unix.com/shell-programming-and-scripting/271790-implementing-linked-list-shell-scripting.html 
me parait trop long.



Je souhaite un exemple bien plus simple, ou bien la suggestion de passer 
de GNU bash à autre chose (je songe peut-être à Python, que je ne 
connais guère).



Pour les aspects "philosophiques" de RefPerSys n'hésitez pas à consulter 
https://afia.asso.fr/journee-hommage-j-pitrat/



Pour un brouillon de papier en anglais (ou même un brouillon très 
incomplet en français), me contacter par courriel


Librement.

--
Basile Starynkevitch
(only mine opinions / les opinions sont miennes uniquement)
92340 Bourg-la-Reine, France
web page: starynkevitch.net/Basile/
Seehttps://github.com/RefPerSys/RefPerSys



Re: exemple en GNU bash de variable tableau

2024-01-29 Thread Michel Verdier
Le 29 janvier 2024 Basile Starynkevitch a écrit :

> J'essaie de collecter dans une variable tableau de bash  files_to_remove les
> fichiers temporaires (qu'il faudrait suprimer à la fin de cez script).

Pourquoi un tableau ? Une simple liste ne suffit pas ?



Re: exemple en GNU bash de variable tableau

2024-01-29 Thread bidons59

Bonjour

Suis certainement à côté de la plaque, mais l'instruction "trap" 
pourrait peut être faire l'affaire?




On 29/01/2024 12:42, didier gaumet wrote:

Bonjour,

Avertissement: j'ai jamais vraiment écrit quoi que ce soit en Bash donc 
ne pas se fier aveuglément à mes paroles


De ce que je comprends, Bash ne gère pas nativement les tableaux 
multi-dimensions (cf la doc Bash):

https://www.gnu.org/software/bash/manual/html_node/Arrays.html

il faut donc contourner cette limitation. Un exemple ici:
https://unix.stackexchange.com/questions/611813/how-to-implement-2d-matrix-using-shell-script





Re: exemple en GNU bash de variable tableau

2024-01-29 Thread didier gaumet

Bonjour,

Avertissement: j'ai jamais vraiment écrit quoi que ce soit en Bash donc 
ne pas se fier aveuglément à mes paroles


De ce que je comprends, Bash ne gère pas nativement les tableaux 
multi-dimensions (cf la doc Bash):

https://www.gnu.org/software/bash/manual/html_node/Arrays.html

il faut donc contourner cette limitation. Un exemple ici:
https://unix.stackexchange.com/questions/611813/how-to-implement-2d-matrix-using-shell-script



exemple en GNU bash de variable tableau

2024-01-29 Thread Basile Starynkevitch

Bonjour la liste

Dans https://github.com/RefPerSys/RefPerSys (un projet de moteur 
d'inférences sous licence GPLv3+ pour Debian) j'essaie de coder un 
script en bash de configuration (simple).


Voir le commit bfb1314 du fichier do-configure-refpersys.bash

(les commentaires sont en mauvais englais)

J'essaie de collecter dans une variable tableau de bash  files_to_remove 
les fichiers temporaires (qu'il faudrait suprimer à la fin de cez script).


Je n'arrive pas à comprendre la syntaxe des variables tableau en GNU bash.

Pour info, mon ordinateur est x86-64 sous Debian/Trixie mis à jour ce matin.

Avec GNU bash, version 5.2.21(1)-release (x86_64-pc-linux-gnu)

Merci de vos eclairages, ou bien d'un exemple (moins de cent lignes de 
GNU bash) qui utilise une variable tableau en y ajouter (dans une 
itération) des éléments (ici des noms de fichiers à supprimer plus tard)



Librement
--
Basile Starynkevitch 
(only mine opinions / les opinions sont miennes uniquement)
92340 Bourg-la-Reine, France
web page: starynkevitch.net/Basile/
See https://github.com/RefPerSys/RefPerSys



Le bash et le zhc ?

2024-01-14 Thread ptilou
Slt,

Bon je commence la formation :
https://www-eni-training-com.bnf.idm.oclc.org/portal/client/video/home
Scripting sous Linux 

Et donc comme au Cnit la Défense un Debiantiste, dont j'ai peut-etre encore les 
cd, m'a dit laisse tomber RedHat, vient chez les vrai 

Oui oui il a dit des choses plus violentes, mais je menage tous le monde !

Et donc quelqu'un a ses support de cours de Jussieu ou de Diderot a me donner ?

Quelqu'un veut la suivre avec moi ?

Ou le monde obscure a envahie le lieu ?

Merci

-- 
Ptilou
J'ai pas d'affichage sous Chrome ? Tu as peur que je sache pecher ?



Re: single quote "'" in bash xterm or lxterminal

2024-01-01 Thread David Wright
On Sun 31 Dec 2023 at 00:43:40 (-0600), Mike McClain wrote:
> I
> suspect logging into a system where you have no home for your primary
> user might get interesting.

That problem is simple to resolve. I have encrypted /home partitions
on all my systems, but the root filesystem has a /home/primaryUser
containing the /etc/skel/* files, in case I should login before
remembering to unock/mount the real /home. (The uncoloured default
prompt makes the mistake obvious.)

What struck me as odd about your narrative was that you place
a configuration file under /mc rather than in the company of
your dotfiles under /home.

Cheers,
David.



Re: single quote "'" in bash xterm or lxterminal

2023-12-30 Thread Mike McClain
Mr. Wooledge,
Long before I realized I could put /home/mike on a separate
partition I started putting my stuff on a separate partition and just
called it /mc. A couple of tomes I had different OS versions on the
same hard drive so it made sense to keep the portions of my stuff that
weren't OS specific in a place I could reach from both OS installs.
Since my tower died and I replaced it with a Raspberry PI, home is on
the uSD. Having /mc on a flash drive means I have it available whether
I'm running debian, devuan or raspbian and if home were on that flash
since those OSs are only similar things could get even more confusing
than they are with my setup. A problem I've not run into but
considered is how to deal with thngs if that flash drive dies. I
suspect logging into a system where you have no home for your primary
user might get interesting.

Mr. Nikulin,
I shouldn't be surprised if xterm-256color is just enough
different from xterm and lxterminal that that is why you don't see a
problem with the '"...": ...' syntax. If you have xterm-256color you
likely have xterm too. Have you tried it?
Thanks for showing me different ways of looking at my challenges.
Happy New Year fellas
Mike
--
Happiness is not so much in having but in sharing.



Re: single quote "'" in bash xterm or lxterminal

2023-12-29 Thread Max Nikulin

On 30/12/2023 09:14, Mike McClain wrote:

Since some of these use a
spinoff of xterm [ -n $DISPLAY ] is a little more generic than
[ $TERM == xterm ], RaspberryPI has chosen lxterminal as their default
which would would fail that test but still runs bash.


I would expect that the reason of failure is

echo $TERM
xterm-256color

so in bash the test should be e.g. [[ "$TERM" == xterm* ]]. The issue 
with $DISPLAY test is that you may start screen or tmux in xterm or 
lxterminal. I am unsure if keys generate the same escape sequences for 
these terminal types.


Conditions in inputrc files are a bit more intelligent in respect to 
terminal types, see readline(3):



Conditional Constructs



term

The  term=  form  may be used to include terminal-specific key bindings,
perhaps to bind the key sequences output by the terminal's function
keys.  The word on the right side of the = is tested against the full
name of the terminal and the portion of the terminal name before the
first -.  This allows sun to match both sun and sun-cmd, for instance.


P.S. I have not managed to reproduce the single quote issue

bind -f /tmp/input-binding
cat /tmp/input-binding
'"\M-[1;5H": backward-kill-line'

bind -p | grep  backward-kill-line
"\C-x\C-?": backward-kill-line

If I strip single quotes then another binding is added successfully.



Re: single quote "'" in bash xterm or lxterminal

2023-12-29 Thread Greg Wooledge
On Fri, Dec 29, 2023 at 08:14:37PM -0600, Mike McClain wrote:
> As it turns out every line in /mc/bin/xterm_bindings that
> was not a comment was problematic.From man readline or info readline
> I saw this: bind '"\C-x\C-r": re-read-init-file' and that is the syntax
> I used in xterm_bindings, as '"\e[1;5H": backward-kill-line'.

Yeah, that's incorrect syntax.  You're dealing with two separate kinds
of things: bind commands issued by a shell, and readline key bindings
read from a file.

When you put a readline key binding into a file like ~/.inputrc or
like your /mc/bin/xterm_bindings file, it looks like this:

"keys": action

But when you do the same thing with bash's bind command, you need to
wrap a *second* layer of quotes around it, like this:

bind '"keys": action'

The outer layer of quotes is removed by the shell, leaving the
readline binding (which includes literal double-quotes) as a single
argument.

You've mixed up the two syntaxes.  That's the source of the problem.

> You wondered what /mc/implied, my name is McClain so /mc is where my
> stuff goes to separate it from system stuff making it easier to move
> my stuff from distribution to distribution.

That's what your home directory is for, though.  It seems odd to keep
personal settings in two separate locations like this.



Re: single quote "'" in bash xterm or lxterminal

2023-12-29 Thread Mike McClain
In response to Greg Wooledge's message of Wed, 27 Dec.
As it turns out every line in /mc/bin/xterm_bindings that
was not a comment was problematic.From man readline or info readline
I saw this: bind '"\C-x\C-r": re-read-init-file' and that is the syntax
I used in xterm_bindings, as '"\e[1;5H": backward-kill-line'.
Looking as you suggested for the problematic line, I deleted each
line until none were left, only then did the "'" problem go away.
When I compared .inputrc to xterm_bindings I then saw the problem.
You wondered what /mc/implied, my name is McClain so /mc is where my
stuff goes to separate it from system stuff making it easier to move
my stuff from distribution to distribution. I started with DosLinux
back around 1997-8 and have used redhat, slakware, solaris, freebsd
and settled on Debian early this century. Since some of these use a
spinoff of xterm [ -n $DISPLAY ] is a little more generic than
[ $TERM == xterm ], RaspberryPI has chosen lxterminal as their default
which would would fail that test but still runs bash.
In spite of having used linux for years I'm still a 'luser'
compared to you and often fumble as this case demonstrates.
I do appreciate your input, bothe here and on the bash list.
Thanks for the help and I wish you a happy new year.
Mike
--
Happiness is not so much in having but in sharing.



Re: single quote "'" in bash xterm or lxterminal

2023-12-27 Thread Greg Wooledge
On Thu, Dec 28, 2023 at 09:15:52AM +0700, Max Nikulin wrote:
> On 26/12/2023 23:57, Mike McClain wrote:
> > Only when xterm_bindings has no executable lines in it does it not
> > kill '"' in an X terminal window.
> > The line that pulled it in was ;
> > [ -n "$DISPLAY" ] && [ -f /mc/bin/xterm_bindings ] && bind -f 
> > /mc/bin/xterm_bindings;
> 
> I do not see anything that may cause the issue with single quote in the
> following message. I am curious what was the goal of the particular binding
> that had so detrimental side effect.
> 
> https://lists.debian.org/msgid-search/20110218064727.GA6305@playground
> Re: xterm question [SOLVED] Thu, 17 Feb 2011 22:47:27 -0800

That message is over 12 years old.  It's quite likely some changes have
been made since then.

I'd also be curious to see which line of the /mc/bin/xterm_bindings
file actually caused the issue.  I'm guessing it was either a typo,
or a conceptual error in setting up the desired binding.

Background info for those following along:

The bind command (a bash builtin) installs readline key bindings --
in this case, from a file named /mc/bin/xterm_bindings.

Readline normally reads custom key bindings from the ~/.inputrc file.
This is done automatically, and does not need a bind command to be
executed from a dot file.

I have no idea why the OP is using this file in addition to, or instead
of, the ~/.inputrc file.

It's *possible* that the OP wanted different key bindings in bash
compared to other programs that use readline, e.g. gdb.  That would
be one reason to keep two separate files.  I have no idea why the
second file is kept outside the user's $HOME, though, let alone why
the OP has a directory named /mc, or why bash-specific readline key
bindings are kept there.

I'm also extremely confused why these bindings are only loaded when
bash is run inside an X session (the $DISPLAY check).  I don't see
the point of that at all.  If anything, a check for $TERM == xterm
might be reasonable (based on the name of the file), but that's not the
check that's being used.



Re: single quote "'" in bash xterm or lxterminal

2023-12-27 Thread Max Nikulin

On 26/12/2023 23:57, Mike McClain wrote:

Only when xterm_bindings has no executable lines in it does it not
kill '"' in an X terminal window.
The line that pulled it in was ;
[ -n "$DISPLAY" ] && [ -f /mc/bin/xterm_bindings ] && bind -f 
/mc/bin/xterm_bindings;


I do not see anything that may cause the issue with single quote in the 
following message. I am curious what was the goal of the particular 
binding that had so detrimental side effect.


https://lists.debian.org/msgid-search/20110218064727.GA6305@playground
Re: xterm question [SOLVED] Thu, 17 Feb 2011 22:47:27 -0800



Re: single quote "'" in bash xterm or lxterminal

2023-12-26 Thread Mike McClain
You guys were rigt all along, I just couldn't see it.
Greg's suggestion to try dash showed me the error of my ways.
I moved .inputrc to no.inputrc, commented out the line in
bash.environment that pulled in xterm_bindings, killed and restarted X
and sure enough I had '"' in an lxterminal window.
I moved no.inputrc back to .inputrc, killed and restarted X and still
had '"' in an lxterminal window.
I deleted half of the entries in xterm_bindings, reenabled the
statement in bash.environment, killed and restarted X and
lost '"' in an lxterminal window.
I deleted another half of the entries in xterm_bindings,
killed and restarted X and  still no '"' in an lxterminal window.
Only when xterm_bindings has no executable lines in it does it not
kill '"' in an X terminal window.
The line that pulled it in was ;
[ -n "$DISPLAY" ] && [ -f /mc/bin/xterm_bindings ] && bind -f 
/mc/bin/xterm_bindings;

Greg I have no idea when this happened xterm_bindings was started in 2011
and either I didn't notice it or it wasn't a big enough problem to
deal with. I keep tty{1-10} open all the time and X only on tty11 so
seldom use a terminal window in X.

Thanks for your help fellows and Happy Holidays,
May the new year be good for you,
Mike
--
Never ascribe to stupidity what can be explained as ignorance.



Re: single quote "'" in bash xterm or lxterminal

2023-12-26 Thread Max Nikulin

On 25/12/2023 12:31, Mike McClain wrote:

In lxterminal control v displays "'" though lxterminal doesn't.


Do xterm and lxterminal behave in a similar way? Is there something 
related to xterm *VT100*translations in the output of


xrdb -query -

I am unsure if there are terminal settings and capabilities that may 
affect "'". Anyway


 echo $TERM

What happens if single quote is typed when "cat" is running?

Does behavior of bash change when it is running in "screen" or "tmux" in 
VT or in a GUI terminal application. They use different terminal types.


To check if bash receives "'" you may attach to it by "strace -p PID" 
running in another window. To get PID you may use "echo $$".


Maybe I have missed it, but it is not clear for me if you use X11 or 
Wayland. However I have no ideas specific to session type.


May it happen that you have configured some input method, e.g. iBus?



Re: single quote "'" in bash xterm or lxterminal

2023-12-25 Thread Greg Wooledge
On Mon, Dec 25, 2023 at 12:35:37PM -0600, Mike McClain wrote:
> root@RPI4b3:~> tty; echo $SHELL; echo "' " | hd

For the record, $SHELL does not tell you what shell you're currently in.
It tells you which login shell your account uses, or which shell
you'd *like* to use when you launch a new xterm (et al.) or when you
shell-escape from programs that offer this feature.

To see what shell you're currently in, try:

ps -p $$

> As this demonstrates, I get single quotes in bash in a VT but not in X.

But you DO get single-quotes in jed in X, or in dash in X?



Re: single quote "'" in bash xterm or lxterminal

2023-12-25 Thread Mike McClain
root@RPI4b3:~> tty; echo $SHELL; echo "' " | hd
/dev/tty1
/bin/bash
  27 20 0a  |' .|
0003

mike@RPI4b3:~> tty; echo $SHELL; echo "' " | hd
/dev/tty6
/bin/bash
  27 20 0a  |' .|
0003

mike@RPI4b3:~> tty; echo $SHELL; echo " " | hd
/dev/pts/1
/bin/bash
  20 0a | .|
0002
The above in a lxterminal window.

mike@RPI4b3:~> tty; echo $SHELL; echo " " | hd
/dev/pts/6
/bin/bash
  20 0a | .|
0002
The above in an term window.

As this demonstrates, I get single quotes in bash in a VT but not in X.

I see the same whether beforre or after executing 'setxkbmap -layout us'.

Suggestions for further exploration?

Merry Christmas,
Mike
--
Under capitalism man exploits man; under socialism the reverse is true'
- Polish Proverb.



Re: single quote "'" in bash xterm or lxterminal

2023-12-25 Thread Greg Wooledge
On Sun, Dec 24, 2023 at 11:31:09PM -0600, Mike McClain wrote:
> I've examined /etc/inputrc, .inputrc, /etc/bash.bashrc, ~/.bashrc,
> /etc/profile, /etc/profile.d/*, ~/.profile, ~/.bash_profile,

OK, you've examined them... and... what did you *see* in them?

When did this problem start to happen, and which of these files
were edited right before then?

Oh, and just for additional data: if you start a terminal, and
then run "dash" (or any other shell that isn't bash), does the
problem go away, or does it still happen?  (I'm pretty sure it'll
go away, same as it does when you run "jed", but it's good to
verify.)



Re: single quote "'" in bash xterm or lxterminal

2023-12-24 Thread Mike McClain
This is reported by "xev" in response to the "'" key:
KeyPress event, serial 48, synthetic NO, window 0x1e1,
root 0x3af, subw 0x0, time 1860575, (170,-87), root:(1005,201),
state 0x10, keycode 48 (keysym 0x27, apostrophe), same_screen YES,
XLookupString gives 1 bytes: (27) "'"
XmbLookupString gives 1 bytes: (27) "'"
XFilterEvent returns: False

In lxterminal control v displays "'" though lxterminal doesn't.
"''" shows nothing and "'a" shows "a",
likewise "'e" = "e", "'o" = "o", etc.

I've examined /etc/inputrc, .inputrc, /etc/bash.bashrc, ~/.bashrc,
/etc/profile, /etc/profile.d/*, ~/.profile, ~/.bash_profile,
both of the latter two just pull in ~/.bashrc which pulls in
bash.{aliases,environment,functions} which are just stuff that started out
in ~/.bashrc but got split out when it got unwieldy.

The only things I've got that tweek the keyboard are
/mc/bin/setkeys which is run by /etc/rc.local
and /mc/bin/xterm_bindings pulled in by bash.environment.
Both of these contain keyboard assignments for bash/readline editing functions
or jed editing functions and don't change how a single quote is handled.
They have been around so long they probably predate my awareness of inputrc.
98% of what is /mc/bin I wrote plus a few things I ran across and kept for
the ideas/lessons they taught.

mike@RPI4b3:~> cat /etc/default/keyboard
# KEYBOARD CONFIGURATION FILE

# Consult the keyboard(5) manual page.
XKBMODEL="pc105"
XKBLAYOUT="us"
XKBVARIANT=""
XKBOPTIONS="compose:lwin"
BACKSPACE="guess"

Durring the hours I've spent exploring this problem it has occured to me to
wonder why I would see this problem only in a desktop terminal window
but not on tty(1-10)? That suggests to me that it is not a readline problem
but I don't know much about keyboard mapping in X or wayland as I'm under now.

Suggestions on where to look next?

Thanks for your ideas and Merry Christmas,
Mike
--
No one's life, liberty, or property is safe while
the legislature is in session.
- Mel Greene's _The_Greatest_Joke_Book_Ever_



Re: single quote "'" in bash xterm or lxterminal

2023-12-23 Thread tomas
On Sat, Dec 23, 2023 at 09:06:47PM -0500, Greg Wooledge wrote:
> On Sun, Dec 24, 2023 at 09:01:09AM +0700, Max Nikulin wrote:
> > On 24/12/2023 07:32, Mike McClain wrote:
> > > when I
> > > type a single quote "'" in bash xterm or lxterminal nothing shows.
> > 
> > May it happen that you have dead keys in your keyboard configuration to type
> > characters with accents? I have never used this feature, so my guess may be
> > wrong. What happens if you type single quote twice "''"? What happens if it
> > is followed by a letter "'a"?
> > 
> > cat /etc/default/keyboard
> > 
> > What is reported by "xev" in response to the "'" key?
> 
> If it were a "dead keys" feature in the keyboard driver, I would expect
> that to affect his text editor as well as his shell.  But he claimed
> that this behavior occurs only in the shell.  That makes me think it's
> a readline key binding that has been mangled.

My thought also. But ruling that out is easy, so... Mike: what happens
if you type the single quote twice in your terminal? What happens if
you type single quote, then space?

Cheers
-- 
t


signature.asc
Description: PGP signature


Re: single quote "'" in bash xterm or lxterminal

2023-12-23 Thread Greg Wooledge
On Sun, Dec 24, 2023 at 09:01:09AM +0700, Max Nikulin wrote:
> On 24/12/2023 07:32, Mike McClain wrote:
> > when I
> > type a single quote "'" in bash xterm or lxterminal nothing shows.
> 
> May it happen that you have dead keys in your keyboard configuration to type
> characters with accents? I have never used this feature, so my guess may be
> wrong. What happens if you type single quote twice "''"? What happens if it
> is followed by a letter "'a"?
> 
> cat /etc/default/keyboard
> 
> What is reported by "xev" in response to the "'" key?

If it were a "dead keys" feature in the keyboard driver, I would expect
that to affect his text editor as well as his shell.  But he claimed
that this behavior occurs only in the shell.  That makes me think it's
a readline key binding that has been mangled.



Re: single quote "'" in bash xterm or lxterminal

2023-12-23 Thread Max Nikulin

On 24/12/2023 07:32, Mike McClain wrote:

when I
type a single quote "'" in bash xterm or lxterminal nothing shows.


May it happen that you have dead keys in your keyboard configuration to 
type characters with accents? I have never used this feature, so my 
guess may be wrong. What happens if you type single quote twice "''"? 
What happens if it is followed by a letter "'a"?


cat /etc/default/keyboard

What is reported by "xev" in response to the "'" key?



Re: single quote "'" in bash xterm or lxterminal

2023-12-23 Thread Greg Wooledge
On Sat, Dec 23, 2023 at 06:32:35PM -0600, Mike McClain wrote:
> I seldom use the command line while on the desk top since I keep 10
> VTs open for day to day tasks so only recently noticed that when I
> type a single quote "'" in bash xterm or lxterminal nothing shows. If
> I open a file for editing with jed, my favorite editor, I can type a
> single quote but back on the CL again no "'".
> Suggestions on where to look for a solution?

Most likely something in your ~/.inputrc file, if you have one.  It
could also be in /etc/inputrc (global version of ~/.inputrc), or in
any dot files that are read during shell startup (~/.bashrc or
/etc/bash.bashrc or other files that are sourced or dotted in by one
of these, including profiles if this is a login shell).

In any case, this sounds very much like a readline binding issue,
which points toward inputrc more than anything else.



single quote "'" in bash xterm or lxterminal

2023-12-23 Thread Mike McClain
I seldom use the command line while on the desk top since I keep 10
VTs open for day to day tasks so only recently noticed that when I
type a single quote "'" in bash xterm or lxterminal nothing shows. If
I open a file for editing with jed, my favorite editor, I can type a
single quote but back on the CL again no "'".
Suggestions on where to look for a solution?

Thanks and Merry Christmas,
Mike
--
Silence & smile are two powerful tools.
Smile is the way to solve many problems
& Silence is the way to avoid many problems.



Re: bash vs. dash and stdin

2023-11-23 Thread Max Nikulin

On 22/11/2023 19:17, Greg Wooledge wrote:

On Wed, Nov 22, 2023 at 07:06:58PM +0700, Max Nikulin wrote:


ssh localhost echo remote
echo local


This is like <https://mywiki.wooledge.org/BashFAQ/089>.  ssh grabs
all of the stdin (until EOF) and leaves none for bash.


Thanks. I expected to find it among pitfalls.


I don't know dash's internals.  Maybe dash reads an entire buffer's
worth of stdin at a time, instead of a command at a time as bash does.


It seems dash reads a block from stdin (and does not lseek back even for 
regular files) only for commands. I do not see significant difference 
when commands reading stdin are placed into a script


cmd='seq 100 | while read -r var ; do
  printf "%s\n" "$var" ;
  ssh localhost echo remote ;
done'
bash -c "$cmd"
dash -c "$cmd"


If the script is passed as an argument, not to stdin, then output contains
"local" in both cases.


Yes.  In that case, bash is not competing with ssh for stdin.


I have found an attempt to report it:

https://lore.kernel.org/dash/6640a8ee-eda0-1e35-df1a-c8b303440...@mail.de/
stdin should be consumed line by line. Fri, 22 Oct 2021 13:11:43 +0200

No response.



Re: bash vs. dash and stdin

2023-11-22 Thread Nicolas George
Max Nikulin (12023-11-22):
> Is there a document that describes shell behavior in respect to stdin in
> such cases?

The shell did not eat your stdin here, ssh did.

Regards,

-- 
  Nicolas George



Re: bash vs. dash and stdin

2023-11-22 Thread Greg Wooledge
On Wed, Nov 22, 2023 at 07:06:58PM +0700, Max Nikulin wrote:
> Consider a file (ssh.sh) containing a couple of commands:
> 
>ssh localhost echo remote
>echo local
> 
> Let's try to run it (assuming key-based authorization)
> 
> bash  remote

You're trying to use stdin twice at the same time.  You've got bash
reading stdin to fetch commands, and you've got ssh reading stdin because
that's just what ssh does.

This is like <https://mywiki.wooledge.org/BashFAQ/089>.  ssh grabs
all of the stdin (until EOF) and leaves none for bash.

> One might expect to see "local" as well.
> 
> dash  remote
> local

I don't know dash's internals.  Maybe dash reads an entire buffer's
worth of stdin at a time, instead of a command at a time as bash does.

> If the script is passed as an argument, not to stdin, then output contains
> "local" in both cases.

Yes.  In that case, bash is not competing with ssh for stdin.



bash vs. dash and stdin

2023-11-22 Thread Max Nikulin

Hi,

There was a thread on stdio buffering and fork a month ago. That time I 
thought shells should be rather careful with input/output handling when 
spawning subprocesses.


Consider a file (ssh.sh) containing a couple of commands:

   ssh localhost echo remote
   echo local

Let's try to run it (assuming key-based authorization)

bash Is there a document that describes shell behavior in respect to stdin in 
such cases?


If the script is passed as an argument, not to stdin, then output 
contains "local" in both cases. I admit that ssh (called this way) can 
not avoid consuming of some stdin, so bash behavior may be considered a 
bit more correct despite initial expectations.


If you are going to try strace then, to make difference more prominent, 
it is better to force creation of a pipe


cat ssh.sh | strace bash

I am curious if it may be a dash bug or it is just falls into the 
category of unspecified behavior.


P.S. I noticed it in a discussion whether a command not executed after 
ssh is an Emacs bug. My conclusion is that "ssh -n" should be used in 
scripts unless a remote command really needs stdin.




Re: Using the bash shell: determine if the root user used 'sudo -i'

2023-08-26 Thread Greg Wooledge
On Sat, Aug 26, 2023 at 06:42:42PM -0400, Karl Vogel wrote:
> If you're running bash, the safest way to find your current working
> directory is capturing the output from /bin/pwd.  Symlinked directories
> can surprise you:
> 
> me$ cd
> 
> me$ ls -ldF today
> lrwxr-xr-x  1 me mis   18 Aug 26 00:03 today@ -> notebook/2023/0826
> 
> me$ cd today
> 
> me$ pwd
> /home/me/today
> 
> me$ /bin/pwd
> /home/me/notebook/2023/0826
> 
> me$ echo $PWD
> /home/me/today

unicorn:~$ help pwd
pwd: pwd [-LP]
Print the name of the current working directory.

Options:
  -Lprint the value of $PWD if it names the current working
directory
  -Pprint the physical directory, without any symbolic links

By default, `pwd' behaves as if `-L' were specified.
[...]

Of course, this is all a big tangent from the original request.



Re: Using the bash shell: determine if the root user used 'sudo -i'

2023-08-26 Thread Karl Vogel
On Sat, Aug 26, 2023 at 12:09:57PM -0400, Tom Browder wrote:
> Excellent mind-reading, Greg! So to use your line I will put in that dir:
> "cd /required-dir || exit"
> 
> Thanks so much.  And thanks to all others who responded.

If you're running bash, the safest way to find your current working
directory is capturing the output from /bin/pwd.  Symlinked directories
can surprise you:

me$ cd

me$ ls -ldF today
lrwxr-xr-x  1 me mis   18 Aug 26 00:03 today@ -> notebook/2023/0826

me$ cd today

me$ pwd
/home/me/today

me$ /bin/pwd
/home/me/notebook/2023/0826

me$ echo $PWD
/home/me/today

If you want to know why you had an early exit:

me$ cat try
#!/usr/bin/env bash
# try: test logging.

export PATH=/usr/local/bin:/bin:/usr/bin
set -o nounset  # check for unbound variables.
tag=${0##*/}
umask 022

# Test file descriptor 2 for interactive or cron use.
test -t 2
case "$?" in
0) logmsg () { echo "$(date '+%F %T') $tag: $@"; } ;;
*) logmsg () { logger -t $tag "$@"; }  ;;
esac

warn () { logmsg "WARN: $@" ; }
die ()  { logmsg "FATAL: $@"; exit 1 ; }

# Real work starts here.
case "$#" in
0)  die "need a directory" ;;
*)  dir="$1" ;;
esac

test -d "$dir" || die "$dir: not a directory"
cd "$dir"  || die "$dir: cannot cd"
cwd=$(/bin/pwd)

logmsg "start working in $cwd"
exit 0

On FreeBSD, you can use "daemon" to run something detached from the
controlling terminal, which simulates running a cron job:

me$ ls -ldF /etc /var/authpf
drwxr-xr-x 27 root wheel  120 26-Aug-2023 07:55:02 /etc/
drwxrwx---  2 root authpf   2 05-Jul-2019 00:45:45 /var/authpf/

me$ ./try /etc
2023-08-26 18:31:54 try: start working in /etc

me$ daemon -f $PWD/try /etc
me$ daemon -f $PWD/try /var/authpf

me$ tail -2 /var/log/syslog
Aug 26 18:19:17 myhost try: start working in /etc
Aug 26 18:19:19 myhost try: FATAL: /var/authpf: cannot cd

Hope this helps.

--
Karl Vogel  I don't speak for anyone but myself.

Oh, my darlin' had bronchitis and she barfed up half a lung,
what came up looked quite amazing when she rolled it on her tongue.
   --sung to the tune of "My Darling Clementine"



Re: Using the bash shell: determine if the root user used 'sudo -i'

2023-08-26 Thread tomas
On Sat, Aug 26, 2023 at 01:54:41PM -0500, Tom Browder wrote:
> On Sat, Aug 26, 2023 at 10:42  wrote:

[...]

> > Basically it is not possible to find out [...]

> As I think I replied earier, I am now checking the script is in the
> required directory in order to be executed (by the root user) [...]

Yes, it seems our posts crossed.

Anyway, glad you found a solution.

Cheers
-- 
t


signature.asc
Description: PGP signature


Re: Using the bash shell: determine if the root user used 'sudo -i'

2023-08-26 Thread Tom Browder
On Sat, Aug 26, 2023 at 10:42  wrote:

> On Sat, Aug 26, 2023 at 04:45:54PM +0200, DdB wrote:
> > Am 26.08.2023 um 16:25 schrieb Tom Browder:
> > > Is there a way to distinguish whether 'sudo -i' was used or not?
> > >
> > Sorry, i am not an expert on this. But ... since years i am using this
> > to check for it:
> >
> > > # if `echo $HOME` is not "/root" or the working dir (pwd) is not
> "/root", then this was not executed with "sudo -i"
> > > assert "echo $HOME" /root "nicht mit sudo -i aufgerufen"
> > > assert pwd /root "nicht mit sudo -i aufgerufen"
> >
> > hope, this will give you a clue ;-)
> > DdB
>
> Unless, of course, the shell does "export HOME=/root" at some point
> after start. Or one of the other fifty-two ways to achieve that.
>
> That's why I think Roberto is right elsewhere in this thread.
>
> Basically it is not possible to find out, so it makes sense to
> think about the question "why do I need this?" to zoom into what
> the real problem is. Perhaps that one can be solved :-)


As I think I replied earier, I am now checking the script is in the
required directory in order to be executed (by the root user). I am not
concerned with any other caveats or use by any unauthorized users for any
nefarious purpose.

I consider this thread completed.

Thanks to all who responded--Debian users are the best!

-Tom


Re: Using the bash shell: determine if the root user used 'sudo -i'

2023-08-26 Thread Nate Bargmann
* On 2023 26 Aug 11:10 -0500, Tom Browder wrote:
> On Sat, Aug 26, 2023 at 10:57 Greg Wooledge  wrote:
> 
> > On Sat, Aug 26, 2023 at 10:49:45AM -0500, Tom Browder wrote:
> > > I would like to know whether 'sudo -i' or 'sudo -s' was used.
> 
> ...
> 
> > In fact, I suspect "I need to know if the cwd is /root" is STILL an X-Y
> > problem.  It's sounding like "I need to ensure my script's working
> > directory is /foo".  If that's truly the case, just do "cd /foo || exit"
> > at the top of the script.
> 
> ...
> 
> Excellent mind-reading, Greg! So to use your line I will put in that dir:
> 
> "cd /required-dir || exit"

In such cases I prefer specifying the complete paths in the script so as
not to get lost.  If the script needs to work in a specific directory of
root I'll put:

cd /root/dir/dir1

or something like:

cd /home/username/dir

and so on (adding whatever error recovery is needed).

If I need to source a file I just type in the complete path name.  It's
a one time bother and the executing shell doesn't care and as the script
gets more complex it's much easier to keep one's bearings on where the
script is working at various points.

As I see it, relative paths are more for interactive shell use.

- Nate

-- 
"The optimist proclaims that we live in the best of all
possible worlds.  The pessimist fears this is true."
Web: https://www.n0nb.us
Projects: https://github.com/N0NB
GPG fingerprint: 82D6 4F6B 0E67 CD41 F689 BBA6 FB2C 5130 D55A 8819



signature.asc
Description: PGP signature


Re: Using the bash shell: determine if the root user used 'sudo -i'

2023-08-26 Thread tomas
On Sat, Aug 26, 2023 at 11:56:27AM -0400, Greg Wooledge wrote:
> On Sat, Aug 26, 2023 at 10:49:45AM -0500, Tom Browder wrote:
> > I would like to know whether 'sudo -i' or 'sudo -s' was used.
> 
> That's STILL an X-Y problem.
> 
> > The reason is
> > to know if the cwd is set to '/root' or '.' It's critical for the script
> > execution
> 
> Oh?  Then just look at the current working directory.  It's in the $PWD
> variable.

I guess it's better use the shell builtin pwd:

  PWD=/not/such/file/or/directory
  echo "cwd=" $(pwd) "PWD=" $PWD

(Note: your shell prompt might be a bit... messed up after
that)

> You don't actually need to know what was typed.

Yep, that was my hunch, too.

Cheers
-- 
t


signature.asc
Description: PGP signature


Re: Using the bash shell: determine if the root user used 'sudo -i'

2023-08-26 Thread Michael Kjörling
On 26 Aug 2023 11:56 -0400, from g...@wooledge.org (Greg Wooledge):
> You don't actually need to know what was typed.

And even being able to answer the question "how was sudo executed"
doesn't solve the problem of ensuring that the script is executing
within a particular directory. All it takes is the user cd'ing to a
different directory before running the script.


> In fact, I suspect "I need to know if the cwd is /root" is STILL an X-Y
> problem.

Agreed.

Also, a few things worth noting:

* The current working directory will ALWAYS be ".". That's what "." at
the beginning of a relative path _means_. So testing the current
working directory against the actual path corresponding to "." will
always return a truthy result.

* The home directory of the root user won't necessarily be /root. By
convention it often is, but there's no guarantee that this is the
case.

* There can be multiple users with the same numerical user ID
(including 0), with different user names and home directories but
access to the same files. The BSDs do this often; Linux systems more
rarely so, but it's absolutely possible.

And that's just what I can think of off the top of my head.

-- 
Michael Kjörling  https://michael.kjorling.se
“Remember when, on the Internet, nobody cared that you were a dog?”



Re: Using the bash shell: determine if the root user used 'sudo -i'

2023-08-26 Thread Tom Browder
On Sat, Aug 26, 2023 at 10:57 Greg Wooledge  wrote:

> On Sat, Aug 26, 2023 at 10:49:45AM -0500, Tom Browder wrote:
> > I would like to know whether 'sudo -i' or 'sudo -s' was used.

...

> In fact, I suspect "I need to know if the cwd is /root" is STILL an X-Y
> problem.  It's sounding like "I need to ensure my script's working
> directory is /foo".  If that's truly the case, just do "cd /foo || exit"
> at the top of the script.

...

Excellent mind-reading, Greg! So to use your line I will put in that dir:

"cd /required-dir || exit"

Thanks so much.

And thanks to all others who responded.

-Tom


Re: Using the bash shell: determine if the root user used 'sudo -i'

2023-08-26 Thread Greg Wooledge
On Sat, Aug 26, 2023 at 10:49:45AM -0500, Tom Browder wrote:
> I would like to know whether 'sudo -i' or 'sudo -s' was used.

That's STILL an X-Y problem.

> The reason is
> to know if the cwd is set to '/root' or '.' It's critical for the script
> execution

Oh?  Then just look at the current working directory.  It's in the $PWD
variable.

You don't actually need to know what was typed.

In fact, I suspect "I need to know if the cwd is /root" is STILL an X-Y
problem.  It's sounding like "I need to ensure my script's working
directory is /foo".  If that's truly the case, just do "cd /foo || exit"
at the top of the script.



Re: Using the bash shell: determine if the root user used 'sudo -i'

2023-08-26 Thread Tom Browder
On Sat, Aug 26, 2023 at 09:32 Roberto C. Sánchez  wrote:

> On Sat, Aug 26, 2023 at 09:25:10AM -0500, Tom Browder wrote:
> >In a previous thread it was shown how to detect a SUDO_USER in a bash
> >shell.
> >Is there a way to distinguish whether 'sudo -i' was used or not?


I would like to know whether 'sudo -i' or 'sudo -s' was used. The reason is
to know if the cwd is set to '/root' or '.' It's critical for the script
execution

-Tom


Re: Using the bash shell: determine if the root user used 'sudo -i'

2023-08-26 Thread tomas
On Sat, Aug 26, 2023 at 04:45:54PM +0200, DdB wrote:
> Am 26.08.2023 um 16:25 schrieb Tom Browder:
> > Is there a way to distinguish whether 'sudo -i' was used or not?
> > 
> Sorry, i am not an expert on this. But ... since years i am using this
> to check for it:
> 
> > # if `echo $HOME` is not "/root" or the working dir (pwd) is not "/root", 
> > then this was not executed with "sudo -i"
> > assert "echo $HOME" /root "nicht mit sudo -i aufgerufen"
> > assert pwd /root "nicht mit sudo -i aufgerufen"
> 
> hope, this will give you a clue ;-)
> DdB

Unless, of course, the shell does "export HOME=/root" at some point
after start. Or one of the other fifty-two ways to achieve that.

That's why I think Roberto is right elsewhere in this thread.

Basically it is not possible to find out, so it makes sense to
think about the question "why do I need this?" to zoom into what
the real problem is. Perhaps that one can be solved :-)

Cheers
-- 
t


signature.asc
Description: PGP signature


Re: Using the bash shell: determine if the root user used 'sudo -i'

2023-08-26 Thread Alain D D Williams
On Sat, Aug 26, 2023 at 09:25:10AM -0500, Tom Browder wrote:
> In a previous thread it was shown how to detect a SUDO_USER in a bash shell.
> 
> Is there a way to distinguish whether 'sudo -i' was used or not?

I have not tested this but if bash was interactive you will find a
.bash_history file in their $HOME.

That assumes that they have not logged in - ie only ever sudo.

> Thanks.
> 
> -Tom

-- 
Alain Williams
Linux/GNU Consultant - Mail systems, Web sites, Networking, Programmer, IT 
Lecturer.
+44 (0) 787 668 0256  https://www.phcomp.co.uk/
Parliament Hill Computers. Registration Information: 
https://www.phcomp.co.uk/Contact.html
#include 



Re: Using the bash shell: determine if the root user used 'sudo -i'

2023-08-26 Thread DdB
Am 26.08.2023 um 16:25 schrieb Tom Browder:
> Is there a way to distinguish whether 'sudo -i' was used or not?
> 
Sorry, i am not an expert on this. But ... since years i am using this
to check for it:

> # if `echo $HOME` is not "/root" or the working dir (pwd) is not "/root", 
> then this was not executed with "sudo -i"
>   assert "echo $HOME" /root "nicht mit sudo -i aufgerufen"
>   assert pwd /root "nicht mit sudo -i aufgerufen"

hope, this will give you a clue ;-)
DdB



Re: Using the bash shell: determine if the root user used 'sudo -i'

2023-08-26 Thread Roberto C . Sánchez
On Sat, Aug 26, 2023 at 09:25:10AM -0500, Tom Browder wrote:
>In a previous thread it was shown how to detect a SUDO_USER in a bash
>shell.
>Is there a way to distinguish whether 'sudo -i' was used or not?
>Thanks.
>-Tom

The SUDO_COMMAND environment variable would report /bin/bash in that
instance. Would that be sufficient for your needs?

If not, then what exactly are you trying to accomplish? Please don't say
"I want to know if sudo -i was used" because we already know that. Why
is that a necessary piece of information in your use case? What will you
do with that information? What decision will you make? What action will
you take?

Regards,

-Roberto

-- 
Roberto C. Sánchez



  1   2   3   4   5   6   7   8   9   10   >