Re: "${assoc[@]@k}" doesn't get expanded to separate words within compound assignment syntax

2024-03-24 Thread Dennis Williamson
On Sun, Mar 24, 2024 at 4:04 PM Greg Wooledge  wrote:

> The @K (capital) transformation gives you quoted strings which need to
> be eval'ed.  Very Bourne-shell-ish.
>
> The @k (lowercase) transformation gives you a list of alternating raw
> key/value strings, like what you'd expect from a Tcl command.
>

I apologize. I didn't test the transforms properly.

>> Thus the @K allows preserving indices in a sparse
>> indexed array.

> Both of them do that:

Yes. I didn't mean to imply that one didn't. The main point I intended to
make was that your statement

>>> The main difference would be that with an indexed array, every argument
after the array name becomes an array element, instead of half of them
being keys and the other half being values.

missed that.

-- 
Visit serverfault.com to get your system administration questions answered.


Re: "${assoc[@]@k}" doesn't get expanded to separate words within compound assignment syntax

2024-03-24 Thread Dennis Williamson
On Sun, Mar 24, 2024 at 1:56 PM Greg Wooledge  wrote:

> It would be pretty reasonable to have a builtin that could take an array
> name plus any number of additional argument pairs, and load those pairs
> as keys/values into said array.  Then you could do something like this:
>
> declare -A hash=(...)
> kvlist=( "${hash[@]@k}" )
>
> declare -A newhash
> addtoarray newhash "${kvlist[@]}"
>
> Some readers may observe that this looks a bit like Tcl's "array set"
> command.  That's not a coincidence.  Whenever I see "a list of alternating
> keys and values", that's where my mind goes.
>
> I'm debating mentally whether this hypothetical new builtin would only
> work with associative arrays, or also double as an "lappend" (append new
> elements to the end of a list/array) if given an indexed array name.
> I'm leaning toward having it be both.  It wouldn't be any *more* confusing
> than the current situation already is.  The main difference would be that
> with an indexed array, every argument after the array name becomes an
> array element, instead of half of them being keys and the other half
> being values.
>
> Then again, I'm not likely to attempt to implement it, so anyone who
> actually writes the code gets to make all the decisions.
>
>
The @K transform outputs key value pairs for indexed arrays as well as
associative arrays (you used the @k transform which does word splitting and
loses the k-v sequence). Thus the @K allows preserving indices in a sparse
indexed array. So your hypothetical builtin would only depend on the type
of the receiving array. So it wouldn't be every argument as an element - it
would still be keys (indices) and values alternating.

declare -A hash=(...)
kvlist=( "${hash[@]@K}" )

declare -A newhash
addtoarray newhash "${kvlist[@]}"

declare -a indexed=(...)# or initialized / built up in another way
- with sequential or sparse indices
kvlist=( "${indexed[@]@K}" )

declare -a newindexed # or omitted
addtoarray newindexed "${kvlist[@]}"

addtoarray should have options for dealing with index collisions (last wins
(default), first wins, error, warning) and a clear before adding would be
handy but trivial to do in a script. Another handy but not needed feature
would be an option to declare the receiving array and add to it in one go.

I'm also unlikely to implement it.

-- 
Visit serverfault.com to get your system administration questions answered.


Re: Make reverse-i-search failure joltingly clear

2023-12-10 Thread Dennis Williamson
On Mon, Dec 11, 2023 at 1:09 AM Dan Jacobson  wrote:

> Type ^R and some string,
> At the point while we are typing that the search fails, all that
> happens is the word "failed" gets added at front,
>
> (reverse-i-search)`nni': set
> jida^Ci.org/geo/house_numbering/grids/us/il/lake/lake_county/
> (failed reverse-i-search)`nnii': set
> jida^Ci.org/geo/house_numbering/grids/us/il/lake/lake_county/
>
> (The ^Cs are where I quit in order to make this "screenshot".)
>
> The average Joe, if looking up at his screen, will mostly just notice
> the line getting longer and longer for each character he types, no
> matter if it started failing many characters ago.
>
> Hmmm, how does emacs handle such situations? Well when the first
> failed character is entered there is a flash. Then every additional
> useless character entered gets a red background.
>
> Anyway Bash could be more aggressive to wake the user up to the fact
> that "He is hiking up the wrong trail. Sending money to candidates who
> already quit the race and shut their accounts."  -- typing for no
> reason.
>
> Let's see, it could flash/beep on each useless character. And or
> refuse to echo them etc.
>
> Anyway, after such improvements the average user, instead of typing
> five or six useless characters before realizing failure has already
> occurred, would type just one or two!
>
> One might say that negative doggy training (beeps, red characters (if
> color turned on), frozen line), wouldn't be needed if the user would
> just please be aware of the word "failed" at the start of the line.
>
> Well that word isn't even in uppercase.
>
>
Bash beeps on each failed character for me. And I can set my terminal to
flash (visual bell) instead of or perhaps in addition to beeping when a
bell character (^G) is transmitted.


-- 
Visit serverfault.com to get your system administration questions answered.


Fwd: Strange results

2023-10-26 Thread Dennis Williamson
-- Forwarded message -
From: Dennis Williamson 
Date: Thu, Oct 26, 2023 at 12:09 PM
Subject: Re: Strange results
To: Victor Pasko 


echo "echo11 ${ASCII_SET:-10:1}"echo "echo11 ${ASCII_SET:-10:1}"

On Thu, Oct 26, 2023 at 9:54 AM Victor Pasko  wrote:

> Hi,
>
> echo9 u
> echo10 u
> And the most strange result
> echo11
>
>  
> !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~
>
> --
>
> -- PSK
>

echo "echo9 ${ASCII_SET:$((a-10)):1}"
echo "echo10 ${ASCII_SET:$((-10)):1}"

Both of these say "output the character that's 10th from the end" which is
"u". What did you expect it to output?

echo "echo11 ${ASCII_SET:-10:1}"

This says, according to the man page:

   ${parameter:-word}
  Use Default Values.  If parameter is unset or null, the
expansion of word is substituted.  Otherwise, the value of parameter is
substituted

which means output "10:1" if ASCII_SET is unset or null. Since it isn't,
the contents of that variable are output giving you a long sequence of
ASCII characters.

-- 
Visit serverfault.com to get your system administration questions answered.


-- 
Visit serverfault.com to get your system administration questions answered.


Re: Assignment to RO variable

2023-08-15 Thread Dennis Williamson
On Tue, Aug 15, 2023 at 8:57 PM Wiley Young  wrote:

> So this behavior of `bash`s seems like a bug to me. I stumbled across it by
> accident.
>
> From within a stack of x3 functions called from a case within a for loop,
> when trying to assign a value to a read-only variable, `printf` and `read`
> both fail with exit codes of 1, and the functions, `case` and `for`
> commands all complete.  When trying effectively the same thing with a
> simple assignment syntax, `x=z`, when the assignment fails, the functions
> return, `case` fails to complete and `for` returns an exit code of 1.
>
> It's probably a pretty rare use case, though. I tried this out on Android
> 12 on a Nokia in Termux and Fedora 38 on an HP in XFCE; that's all I've got
> for the time being. There isn't any pressing need to look into this one;
> I'm just curious. A reproducer's attached.
>
> Thanks & Happy summer,
> Wiley
>
> ###
> $ cat ro-var-in-fn.sh
> #!/bin/bash -x
>
> reset
> readonly x=y
> declare -p x SHELLOPTS BASHOPTS
> : "hyphen: $-"
>
> a(){ : go a; b $1; : end a;}
> b(){ : go b; c $1; : end b;}
> c(){
>   : go c
>   declare -p x
>
>   case "$1" in
> 1 )
>   false
>   : "exit, false: $?"
>   ;;
> 2 )
>   printf -v x '%s' $1
>   : "exit, printf: $?"
>   ;;
> 3 )
>   read -r x <<< $1
>   : "exit, read: $?"
>   ;;
> 4 )
>   x=$1
>   : "exit, var assignment: $?"
>   ;;
> 5 )
>   echo $1
>   ;;
>   esac
>   : "exit, case: $?"
>   : end c
> }
>
> declare -pf a b c
>
> for ii in {1..5}
> do
>   a $ii
>   : "exit, a $ii: $?"
> done
> : "exit, for loop: $?"
>
> ###
>

You have assigned the character "y" to the variable "x" which you've set to
read only using the readonly built. It is forever and always immutable (or
the shell it exists in exits).

>From man bash:

readonly [-aAf] [-p] [name[=word] ...]
  The given names are marked readonly; the values of these
names may not be changed by subsequent assignment.  If the -f option is
supplied, the functions
  corresponding to the names are so marked.  The -a option
restricts the variables to indexed arrays; the -A option restricts the
variables to associative arrays.  If
  both options are supplied, -A takes precedence.  If no name
arguments are given, or if the -p option is supplied, a list of all
readonly names is printed.  The
  other options may be used to restrict the output to a subset
of the set of readonly names.  The -p option causes output to be displayed
in a format that may be
  reused as input.  If a variable name is followed by =word,
the value of the variable is set to word.  The return status is 0 unless an
invalid option is
  encountered, one of the names is not a valid shell variable
name, or -f is supplied with a name that is not a function.

Your subsequent attempts to change the value of x will result in readonly
variable errors with a return status is 1 which will affect any logic
making use of it.

Don't use readonly unless you really mean it.

You should use more quotes around variables.

b "$1"
echo "$1"

Your use of colon as a comment character is confusing.

-- 
Visit serverfault.com to get your system administration questions answered.


Re: built-in printf returns success when integer is out of range

2023-07-26 Thread Dennis Williamson
On Wed, Jul 26, 2023, 3:40 PM  wrote:

> Configuration Information [Automatically generated, do not change]:
> Machine: x86_64
> OS: linux-gnu
> Compiler: gcc
> Compilation CFLAGS: -g -O2 -fstack-protector-strong -Wformat
> -Werror=format-security -Wall
> uname output: Linux fnord42 6.1.25-1rodete1-amd64 #1 SMP
> PREEMPT_DYNAMIC Debian 6.1.25-1rodete1 (2023-05-11) x86_64 GNU/Linux
> Machine Type: x86_64-pc-linux-gnu
>
> Bash Version: 5.2
> Patch Level: 15
> Release Status: release
>
> Description:
> printf '%d\n' 111 && echo success
> prints "success"
> /usr/bin/printf does not, but instead returns EXIT_FAILURE (1).
>
> Repeat-By:
> Run:
> printf '%d\n' 111 && echo success
>
>


You didn't include all the output. It's treated as a warning rather than an
error. That's why an error status isn't set.


Re: [PATCH 1/2] <<# indent-stripping heredoc

2023-07-14 Thread Dennis Williamson
On Fri, Jul 14, 2023, 3:44 AM Grisha Levit  wrote:

> On Fri, Jul 14, 2023 at 3:44 AM Martin D Kealey 
> wrote:
> >
> > On the whole I think this is great, and thankyou for working up the
> patch, but I would like to offer some comments and suggestions:
>
> Thanks for looking at it, feedback very much appreciated.
>
> > One option that some other languages use is to find the terminator, and
> then use its indentation as the pattern to remove from the content lines.
> The problem of course is that it would take a double run over the content,
> but the benefit is that there'd only be one in-band signaling line instead
> of two.
>
> I agree, this would be useful functionality, would be interested in
> seeing your implementation.
>
> > Secondly, the battle for 8-space tabs has been well and truly lost at
> this point, so hard-coding that constant feels like it's likely to be a
> source of errors.
> >
> > In order to be tab-agnostic, I can see two reasonable options:
> > 1. remove only an exact match for the sequence of whitespace characters
> that occurs in the indicator line
>
> I think a problem with this is that a coding style using mixed
> tabs/spaces (such as the bash source..) would have
>
> foo
>   EOF
>
> saved as:
>
> [tab]foo
> [spc][spc][spc][spc][spc][spc]EOF
>
>
> so I don't think it's feasible to record the indent level as a fixed
> tab/space mix if we are to allow indentation deeper into the heredoc
> using the document's native style, at least not without ending up back
> at the problem of needing to pick a tab stop width to use.
>
> Personally, I don't use this indentation style (but don't wish to
> precipitate an argument everyone is surely tired of) so I don't have
> much of an opinion on what would be useful here.  One slight point in
> favor of keeping the 8-space wide tab approach is that this is how
> readline renders literal tabs as well.
>


Would a declared spaces-per-level indent amount be useful? Something like
<<4# that would be the script writer's responsibility to conform to since
they set it. This might be in addition to the already proposed <<#.

>


Re: Document m=1 m=2; echo $m result

2023-07-03 Thread Dennis Williamson
On Mon, Jul 3, 2023 at 11:11 AM alex xmb ratchev  wrote:

>
>
>
> thats a like 30% or smth
> enuff for me
> i d be the fool typing nonsensly ; s
>

Do what you like, but percentages don't mean anything unless you're running
a lot of assignments in a loop like the artificial conditions in the test I
showed. A few microseconds (the absolute number - not a percentage) really
won't make a difference in very many scripts.

I write for readability and maintainability. Sometimes chaining assignments
(this may have a better name - Bash doesn't support this type: a=$b=$c) or
multiple assignments separated by semicolons makes sense for organization,
etc. But I almost always write one statement per line - command,
assignment, etc. I even put then and do on their own lines (but that's just
a style choice).

-- 
Visit serverfault.com to get your system administration questions answered.


Re: Document m=1 m=2; echo $m result

2023-07-03 Thread Dennis Williamson
On Mon, Jul 3, 2023 at 10:32 AM alex xmb ratchev  wrote:

>
> i chain assignments , have impression its faster
>
> kre
> >
> >
> >
>

Tests are better than impressions. Sometimes they match though.

$ time for ((i = 0; i <= 100; i++)); do j=$i; k=$j; m=10;
n=foobarbazqux; p=100; q=$n; r=$k; s=$i$j$k$m$n$p$q$r; done

real 0m24.542s
user 0m23.440s
sys 0m0.199s
$ time for ((i = 0; i <= 100; i++)); do j=$i k=$j m=10 n=foobarbazqux
p=100 q=$n r=$k s=$i$j$k$m$n$p$q$r; done

real 0m17.087s
user 0m16.679s
sys 0m0.129s

But at about 8 microseconds per iteration I don't think it's enough of a
difference to choose it for speed alone.

-- 
Visit serverfault.com to get your system administration questions answered.


Re: Funny behaviour of associative arrays

2023-06-27 Thread Dennis Williamson
On Tue, Jun 27, 2023 at 12:29 AM n952162  wrote:

> Is this correct?
>
> declare -A l1
>
> l1=([a]=b [c]=d)
> echo ${!l1[@]}
>
> l1=($(echo [a]=b [c]=d))
> echo ${!l1[@]}
>
> $ bash  t4
> c a
> [a]=b [c]=d
>
> If so, why?  And how can I assign a list of members to an associative
> array?
>

What is t4? Is that a script that contains the lines above?

Your first assignment is a way to assign a list of members to an
associative array. Your second assignment creates a single element with the
index "[a]=b [c]=d" which has a null value.

If you want to see the structure (keys and values) of an array or see the
values of any variable, use declare -p for the most clarity.

$ declare -A l1

$ l1=([a]=b [c]=d).   # assignment of a list of keys and values
$ declare -p  l1
declare -A l1=([c]="d" [a]="b" )

$ l1=($(echo [a]=b [c]=d)).   # not what you want
$ declare -p  l1
declare -A l1=(["[a]=b [c]=d"]="" )

-- 
Visit serverfault.com to get your system administration questions answered.


Re: It is possible that this can be a bug

2023-06-26 Thread Dennis Williamson
On Mon, Jun 26, 2023, 2:47 PM Hugo Napoli  wrote:

> Dear Dennis and Martin, thank you very much for the quick response.
>
> From now on, I'll use *exec bash "$0" *instead of *bash "$0"*.
> What I'm wondering is (now that I understand why this happened) if there
> is some special situation where it's actually worth using *bash "$0"*. If
> you have any ideas, I will really appreciate it if you can share them with
> me.
>
> As for using *a=$((b+c))*, I'll also start using *((a=b+c))* whenever
> possible, leaving out the "$", as suggested.
>
> Thank you very much, also, for the examples you have shown me. I have
> learned BASH mostly self-taught. I think this is why I have been making
> these mistakes.
>
>
> *Hugo Napoli *
>
>>
>>
>>
I would suggest that you use a loop as shown in Greg's message. I answered
showing exec since it followed the structure of your original script. It's
very unusual to use that technique in a script such as yours. I apologize
for not providing better guidance.

Also using $0 only works in certain circumstances and shouldn't be relied
on in all cases. https://mywiki.wooledge.org/BashFAQ/028

>


Re: It is possible that this can be a bug

2023-06-26 Thread Dennis Williamson
On Mon, Jun 26, 2023, 11:07 AM Hugo Napoli  wrote:

> Good day.
>
> Something strange is happening to me with this script that I have designed
> moments ago.
> I am a Computer Science professor, and among the subjects I teach, there is
> one that has to do with BASH programming.
> I make my own material, therefore, I have been working since last year with
> this compendium of exercises that I have created, but I had never noticed
> before that the BASH output of this program could be a "bug".
> If not, I apologize and I'm sorry for wasting your time.
>
> *This is the script code, exactly as I have it in my computer:*
>
> #!/bin/bash
>
> clear
>
> echo ""
> read -p "Ingrese  un  número entero de hasta 2 cifras
>   : " min
> read -p "Ingrese otro número entero de hasta 2 cifras, mayor que el
> anterior  : " max
>
> if [[ ${#min} -gt 2 ]] || [[ ${#max} -gt 2 ]];then
> clear
> echo "" && echo "Deben ser números de hasta 2 cifras..."
> read -p "Pulse ENTER para continuar..."
> bash "$0"
> fi
>
> if [[ $min == $max ]];then
> suma=$((min+max))
> else
> for((c=$min;c<=max;c+=1))
> do
> suma=$((suma+c))
> done
> fi
>
> echo ""
> echo "La suma entre "$min" y "$max", es "$suma"."
> echo ""
>
> *This is the output when I type "222" and "222" for min and max,
> respectively, and in the next try, I enter "2" and "2":*
>
> Ingrese  un  número entero de hasta 2 cifras : 2
> Ingrese otro número entero de hasta 2 cifras, mayor que el anterior  : 2
>
> La suma entre 2 y 2, es 4.
>
>
>
> *La suma entre 222 y 222, es 444.*
>
> What is in red is what I understand should not happen: the program repeats
> the same operation, when the "bash $0" is supposed to reinitialize the
> program and show only one result, not 2.
> And if I enter 3, 4, or 5 wrong values, I get 3, 4, 5 additional results,
> respectively.
>
> Before writing this report, I ran the same script on Arch Linux, getting
> exactly the same results.
>
> *I'm using openSUSE 15.4 (Leap, updated until today and phisically
> installed, not virtualized) with "KDE Plasma desktop 5.24.4, Frameworks
> 5.90.0, Qt 5.15.2 running on X11" and kernel "5.14.21-150400.24.63-default"
> and I execute all my scripts in "Konsole", now in 21.12.3 version. The
> hardware is AMD Ryzen 3 3200U in an ACER Aspire 5 machine.*
>
> I will be at your service for whatever you need to ask me.
>
> Receive a warm hug from Uruguay,
>
>
> *Hugo Napoli*
>
> *Espacio educativo en YouTube:
> https://www.youtube.com/c/entropíabinaria
> *
> *Sitio web personal:**https://hugonapoli.blogspot.com/*
> 
>
> *Si vas a reenviar este correo:*
> *-* te agradezco que antes de hacerlo, elimines mi dirección de correo
> electrónico.
> *-* en lugar de poner las direcciones en el renglón "PARA", ponlas en
> "CCO". De este modo,
>   estarás contribuyendo a que tus contactos no reciban virus y spam por
> mail.
> *>* Utilicemos el correo electrónico con responsabilidad.
>
> *Haz clic aquí para informarte en Wikipedia*
> 
>

bash "$0"

calls the script as a sub-program without any arguments.

To replace the current script with a new instance use

exec bash "$0"


Re: Fwd: Command execution by creating file.

2023-06-20 Thread Dennis Williamson
On Tue, Jun 20, 2023 at 10:55 PM LitHack  wrote:

> Sorry instead of alias we have to use the function.
>
> Corrected command: mkdir dir;cd dir;<>file;file()bash;*
>
> Thanks and regards.
>


You don't need the function either.

mkdir dir; cd dir; touch bash; *


-- 
Visit serverfault.com to get your system administration questions answered.


Re: New array_expand_once option

2023-06-17 Thread Dennis Williamson
On Sat, Jun 17, 2023, 6:59 AM alex xmb ratchev  wrote:

> On Thu, Jun 15, 2023, 20:40 alex xmb ratchev  wrote:
>
> >
> >
> > On Thu, Jun 15, 2023, 15:06 Chet Ramey  wrote:
> >
> >> On 6/14/23 5:18 PM, alex xmb ratchev wrote:
> >>
> >> > [[ -v a["$subscript"] ]]
> >>
> >
> a small question about that .. do the quotes matter ?
>
>


Try it without the quotes and with an empty or unset  variable.

>


Re: Searches in bash don't works

2023-05-24 Thread Dennis Williamson
On Wed, May 24, 2023, 5:21 PM William via Bug reports for the GNU Bourne
Again SHell  wrote:

> Hi. It's the first time I send a message about a bug using bashbug. I
> don't known if the message was sent properly. So, I repeat it that way.
>
>
> Machine: i686
>
> OS: linux-gnu
> Compiler: gcc
> Compilation CFLAGS:  -DPROGRAM='bash' -DCONF_HOSTTYPE='i686'
> -DCONF_OSTYPE='linux-gnu' -DCONF_MACHTYPE='i686-pc-linux-gnu'
> -DCONF_VENDOR='pc' -DLOCALEDIR='/usr/share/locale' -DPACKAGE='bash'
> -DSHELL -DHAVE_CONFIG_H   -I.  -I../. -I.././include -I.././lib
> -D_FORTIFY_SOURCE=2 -g -O2 -fstack-protector --param=ssp-buffer-size=4
> -Wformat -Werror=format-security -Wall
> uname output: Linux equipo 4.4.0-210-generic #242~14.04.1-Ubuntu SMP Fri
> Apr 16 15:02:48 UTC 2021 i686 i686 i686 GNU/Linux
> Machine Type: i686-pc-linux-gnu
>
> Bash Version: 4.3
> Patch Level: 11
> Release Status: release
>
> Description:
>  [Detailed description of the problem, suggestion, or complaint.]
> *Simply, searching only shows coincidences in the visible text of the
> window.*
> Repeat-By:
>  [Describe the sequence of events that causes the problem
>  to occur.]
> *You search anything; if the term is not visible in the window, you
> don't obtain results. If you scroll, you can obtain a result if visible.**
> **Fix:*
>  [Description of how to fix the problem.  If you don't know a
>  fix for the problem, don't include this section.]
>

I think you're probably describing an issue with your terminal rather than
with Bash. How do you perform the search (what key do you press or menu do
you select)? Specific and detailed answers to questions like this are what
should be provided in the "Describe the sequence" section rather than
general conceptual descriptions.

If the problem is with your terminal you will need to contact support for
it or for the distribution or operating system that provides it.

>


Re: Bash Reference Manual Type

2023-03-31 Thread Dennis Williamson
On Fri, Mar 31, 2023, 3:02 PM Martin Schulte 
wrote:

> Hi Dennis,
>
> thanks for your answer!
>
> > This isn't regex.
>
> Sure!
>
> > It's a command synopsis using a long standing notation
> > style. You can see it set out in POSIX in
> >
> https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap12.html#tag_12
> >
> > You'll see this used in many man pages, usage messages and other
> > documentation. It's by no means specific to Bash.
>
> I would be interested in an example!
>
> Best regards,
>
> Martin
>

Examples of man pages and help text:

man man
man grep
grep -h
man find
man ssh
ssh --help
man lsof
lsof -h

An example of the synopsis section of the lsof man page Revision-4.91 on my
Mac:

SYNOPSIS
   lsof  [ -?abChlnNOPRtUvVX ] [ -A A ] [ -c c ] [ +c c ] [ +|-d d ] [
+|-D D ] [ +|-e s ] [ +|-E ] [ +|-f [cfgGn] ] [ -F [f] ] [ -g [s] ] [
   -i [i] ] [ -k k ] [ -K k ] [ +|-L [l] ] [ +|-m m ] [ +|-M ] [ -o [o]
] [ -p s ] [ +|-r [t[m]] ] [ -s [p:s] ] [ -S [t] ] [ -T [t] ] [
   -u s ] [ +|-w ] [ -x [fl] ] [ +|-X ] [ -z [z] ] [ -Z [Z] ] [ -- ]
[names]

Part of the output of lsof -h:

usage: [-?abhlnNoOPRtUvVX] [+|-c c] [+|-d s] [+D D] [+|-f[cgG]]
 [-F [f]] [-g [s]] [-i [i]] [+|-L [l]] [+|-M] [-o [o]] [-p s]
 [+|-r [t]] [-s [p:s]] [-S [t]] [-T [t]] [-u s] [+|-w] [-x [fl]] [--]
[names]

(Side notes: the missing spaces are just as it was output, some options
aren't shown in the help output, -e for example)

I apologize if the formatting of the preceding is unreadable. They are
direct copy/pastes.

>


Re: Bash Reference Manual Type

2023-03-31 Thread Dennis Williamson
On Fri, Mar 31, 2023, 2:47 PM Martin Schulte 
wrote:

> Hi Chet!
>
> > >> Thanks for the report. The synopsis should read
> > >>
> > >> cd [-L|[-P [-e]]] [-@] [dir]
> > >   ^   ^
> > > But aren't these two brackets just superfluous?
> >
> > -L and -P are mutually exclusive, and -e is valid only when -P is
> > supplied.
>
> Yes, my feeling was just that | has such a low precedence that the marked
> pair of brackets could be omitted, like in
>   id|cut -c1-3
> or in the ERE
>   ^(-L|-P( -e)?)?$
>
> But situation seems to be different here.
>
> Best regards,
>
> Martin
>


This isn't regex. It's a command synopsis using a long standing notation
style. You can see it set out in POSIX in
https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap12.html#tag_12

You'll see this used in many man pages, usage messages and other
documentation. It's by no means specific to Bash.


Re: Multiline editing breaks if the previous output doesn't end in newline

2022-10-30 Thread Dennis Williamson
On Sun, Oct 30, 2022 at 4:41 PM Alex fxmbsw7 Ratchev 
wrote:

>
>
> i coded a files tree to bash code via gawk reading and printing bash code
> i did noeol no newline at end
> logically , cause , who wants var='from file\n'
>
> >
>

Because command substitution strips trailing newlines?

$ echo -e 'foo\n\n\n'
foo



$ s=$(echo -e 'foo\n\n\n')
$ declare -p s
declare -- s="foo"

No gyrations needed.
-- 
Visit serverfault.com to get your system administration questions answered.


Re: bash core dumps doing glob pattern on long string

2022-10-11 Thread Dennis Williamson
On Tue, Oct 11, 2022, 3:12 PM Greg Wooledge  wrote:

> On Tue, Oct 11, 2022 at 12:38:44PM -0700, Koichi Murase wrote:
> > As far as I know, glob/extglob
> > does not have constructs that cannot be represented by formal regular
> > languages so should always be able to be represented by NFAs and thus
> DFAs.
>
> It's been too many decades since I studied this stuff in college, but
> earlier while reading the thread I was pondering converting extglobs
> into (ERE) regular expressions.
>
> Extglobs add 5 features:
>
>   ?(pattern-list)
>  Matches zero or one occurrence of the given patterns
>   *(pattern-list)
>  Matches zero or more occurrences of the given patterns
>   +(pattern-list)
>  Matches one or more occurrences of the given patterns
>   @(pattern-list)
>  Matches one of the given patterns
>   !(pattern-list)
>  Matches anything except one of the given patterns
>
> The first 4 can be converted directly into ERE without any issues at all.
> The last one cannot.  At least not easily.
>
> The part I can't remember is whether !(foo) can be expressed in a regular
> language.  My gut says "no", but there might be some trick that I've
> forgotten.  A regular language has concatenation (abc), union (abc|def),
> and close (a*bc*) but not negation.
>


Can't you just match and negate?

>


Re: read problem

2022-09-24 Thread Dennis Williamson
On Sat, Sep 24, 2022 at 11:02 AM kurt  wrote:

> Configuration Information [Automatically generated, do not change]:
> Machine: x86_64
> OS: linux-gnu
> Compiler: gcc
> Compilation CFLAGS: -g -O2 -flto=auto -ffat-lto-objects -flto=auto
> -ffat-lto-objects -fstack-protector-strong -Wformat -Werror=format-security
> -Wall
> uname output: Linux kurt-OptiPlex-7020 5.15.0-48-generic #54-Ubuntu SMP
> Fri Aug 26 13:26:29 UTC 2022 x86_64 x86_64 x86_64 GNU/Linux
> Machine Type: x86_64-pc-linux-gnu
>
> Bash Version: 5.1
> Patch Level: 16
> Release Status: release
>
> Description:
> read into an array is inconsistent depending on the value of IFS
> (tested with ! and ).
> as compared to readarray, which does the expected splitting count
> on both values.
>
> Code to test the problem:
>
> declare -a aa adelim=("!" $'\t')
> declare s delim
> declare -i i j
> for((j=0;j<${#adelim[@]};j++)) do
>   delim="${adelim[$j]}"
>   printf -- 'delim is >%s<\n' "${delim}"
>   s="."
>   for((i=0;i<12;i++)) do
> if [[ $i -gt 4 && $i -lt 9 ]]; then
>   s+="${delim}"
> else
>   s+="${delim}$i"
> fi
>   done
>   printf -- '  >%s<\n' "$s"
>   readarray -d "${delim}" aa <<< "$s"
>   printf -- '  len readarray: %d\n' "${#aa[@]}"
>   IFS="${delim}" read -a aa <<< "$s"
>   printf -- '  len read : %d\n' "${#aa[@]}"
> done
>
> Output is:
>
> delim is >!<
>   >.!0!1!2!3!4!9!10!11<
>   len readarray: 13
>   len read : 13
> delim is >  <
>   >.0   1   2   3   4
>  9   10  11<
>   len readarray: 13
>   len read : 9
>
> Expected for read would also be 13 when IFS is set to .
>
>
>
>From man bash:

   The shell treats each character of IFS as a delimiter, and splits
the results of the other expansions into words on these characters.  If
   IFS is unset, or its value is exactly , the
default, then any sequence of IFS characters serves  to  delimit  words.
   If IFS has a value other than the default, then sequences of the
whitespace characters space and tab are ignored at the beginning and end
   of the word, as long as the whitespace character is in the value of
IFS (an IFS whitespace character).  Any character in IFS that is  not
   IFS  whitespace,  along  with  any adjacent IFS whitespace
characters, delimits a field.  A sequence of IFS whitespace characters is
also
   treated as a delimiter.  If the value of IFS is null, no word
splitting occurs.

Note in particular the next-to-last sentence that begins with "A sequence".
IFS is used by read but not readarray which has its own delimiter argument.
See the manual sections for the two commands.

-- 
Visit serverfault.com to get your system administration questions answered.


Re: Light weight support for JSON

2022-08-28 Thread Dennis Williamson
On Sun, Aug 28, 2022 at 7:47 PM Dale R. Worley  wrote:

> The "obvious" way to support Json in Bash would be a utility that parses
> Json and produces e.g. a Bash associative array, and conversely a
> utility that reads a Bash associative array and produces Json.  The real
> limitation is that it's difficult to have a subprocess set Bash's
> variables.  As far as I know, there's no good idiom for that.
>
> Dale
>
>
If your json_util outputs a Bash declare -A statement then you could just
eval it to get your associative array.

The utility would need to guarantee against code injection in its output.
Another issue is that JSON can express things that Bash associative arrays
can't and so then you get into a rat's nest of workarounds.


-- 
Visit serverfault.com to get your system administration questions answered.


Re: ${!#} doesnt get into history in interactive

2022-08-24 Thread Dennis Williamson
On Wed, Aug 24, 2022, 9:07 AM Alex fxmbsw7 Ratchev 
wrote:

> debian 5.2.0(1)-beta bash
>
> i did code lightly in interactive
> then i did
>
> set -- 1 2 3
> echo ${!#}
>
> then arrow up
> .. both cmds were skipped , and on the term was rather the old code , which
> i previously wrote
>
> then i did
>
> echo ${!#}
>
> arrow up
> .. the old cmd again
>
> attached is a pic from camera on that screen
>
> imo i dont have much in bashrc
> pic of that also
>

set +o histexpand

>


Re: How come math/arithmetic cannot work by set -x

2022-08-12 Thread Dennis Williamson
On Fri, Aug 12, 2022 at 6:51 PM Budi  wrote:

> It doesn't work means no use on set -x, no value is shown
>
> On 8/13/22, Dennis Williamson  wrote:
> > On Fri, Aug 12, 2022, 6:28 PM Budi  wrote:
> >
> >> How come math/arithmetic ((i=k+l)) cannot make use of set -x
> >>
> >> Please help..
> >> (so annoying).
> >>
> >
> >
> > It works for me. What are you expecting?
> >
> > It would help if you show what you're doing, the result you're getting
> and
> > what you expect instead.
> >
> > "It doesn't work" conveys no information whatsoever.
> >
> >>
> >
>

Hmmm... interesting.

$ set -x; unset a; b=2; c=7; ((a = $b + $c)); echo "$a $b $c"; set +x

+ unset a
+ b=2
+ c=7
+ (( a = 2 + 7 ))
+ echo '9 2 7'
9 2 7
+ set +x

shows the values in the arithmetic expression, but

set -x; unset a; b=2; c=7; ((a = b + c)); echo "$a $b $c"; set +x

+ unset a
+ b=2
+ c=7
+ (( a = b + c ))
+ echo '9 2 7'
9 2 7
+ set +x

without the dollar signs doesn't.

Also, note that this message includes a thorough example of doing, result,
expecting.

-- 
Visit serverfault.com to get your system administration questions answered.


Re: How come math/arithmetic cannot work by set -x

2022-08-12 Thread Dennis Williamson
On Fri, Aug 12, 2022, 6:28 PM Budi  wrote:

> How come math/arithmetic ((i=k+l)) cannot make use of set -x
>
> Please help..
> (so annoying).
>


It works for me. What are you expecting?

It would help if you show what you're doing, the result you're getting and
what you expect instead.

"It doesn't work" conveys no information whatsoever.

>


Re: $(()): "?:": false "assignment to non-variable"

2022-07-11 Thread Dennis Williamson
On Mon, Jul 11, 2022 at 8:22 AM Chet Ramey  wrote:

> The normal rules of precedence apply, and the conditional expression on the
> rhs of the `:' can't contain an assignment, since the assignment operator
> has higher precedence.
>
>
This excerpt from the Bash man page ARITHMETIC EVALUATION section:

   expr?expr:expr
  conditional operator
   = *= /= %= += -= <<= >>= &= ^= |=
  assignment

indicates that assignment has a lower precedence than the overall ternary
without specifying precedence of individual parts of it.

Interestingly, zsh requires both assignments to be parenthesized and ksh
doesn't require either. Bash is like C and ksh is like cpp.


declare +attribute in help

2022-06-29 Thread Dennis Williamson
In help declare it says:

Using `+' instead of `-' turns off the given attribute.

In the Bash man page it says:

Using `+' instead of `-' turns off the attribute instead, with the
exceptions that +a and +A may not be used  to  destroy  array variables and
+r will not remove the readonly attribute.

The help text needs to be updated to reflect this limitation. Something
like:

Using `+' instead of `-' turns off the given attribute except for a, A
and r.


-- 
Visit serverfault.com to get your system administration questions answered.


Re: Buffer Overflow

2022-04-12 Thread Dennis Williamson
On Tue, Apr 12, 2022, 3:18 PM Sergio Fuentes <
fuentes.sergio.nov2...@gmail.com> wrote:

> Hello,
>
> Please, run the following 3 commands to reproduce the bug:
>
> echo '. ./poc.sh' > poc.sh
> chmod +x poc.sh
> bash -c './poc.sh'
>
> The backtrace from gdb:
> gdb /bin/bash core
> ...
> Program terminated with signal SIGSEGV, Segmentation fault.
> #0  0x5612fcdece65 in yyparse ()
> (gdb) bt
> #0  0x5612fcdece65 in yyparse ()
> #1  0x5612fcde3869 in parse_command ()
> #2  0x5612fce511fc in parse_and_execute ()
> #3  0x5612fce50837 in ?? ()
>
> Best regards and thanks,
> fs
>

Patient: "Doctor, it hurts when I do this."

Doctor: "Don't do that."

You created a script which calls itself repeatedly. That's what happens
when you do that.

What is it that you're actually trying to do?

>


Re: [Bug Report] The Unexpected Behavior When Using ANSI Escape Code

2022-03-21 Thread Dennis Williamson
On Mon, Mar 21, 2022 at 4:01 AM Michaelll Lee  wrote:

> . . .
> While using non-printing characters without "\[...\]" proves to be fine in
> versions prior to 5.x.x (e.g., many suggestions from some online forums
> have suggested "PS1=\e[0m" for using ANSI escape code in the prompt), the
> same configuration in 5.x.x is not as stable as the previous versions(i.e.,
> "PS1=\[\e[0m\]" should be used instead of "PS1=\e[0m", otherwise the
> unexpected behavior(STEP7) will happen).
> . . .


Note that the difference you see in Bash 5 is due to new paste behavior.
However, prior versions are *not* fine without the escaped brackets. Bash
loses track of the position of the cursor if there are unbracketed
non-printing sequences. This is visible when stepping back through commands
in history and a long command wraps, for an example.
https://mywiki.wooledge.org/BashFAQ/053


Re: Sus behaviour when cmd string ends with single backslash

2022-02-13 Thread Dennis Williamson
On Sun, Feb 13, 2022, 9:48 PM Robert Elz  wrote:

> Date:Sun, 13 Feb 2022 21:38:19 -0500
> From:"Dale R. Worley" 
> Message-ID:  <87o83a895w@hobgoblin.ariadne.com>
>
>   | The two a-priori plausable behaviors are for the backslash to be taken
>   | literally (which is what happens) or for it to vanish as some sort of
>   | incomplete escape construct.
>
> In most places, an unquoted trailing backslash (ie: followed by
> nothing) produces unspecified results.  If you want a \ then
> quote it ( \\ will do, as would '\', but not "\" for the obvious
> reason...).
>
> When used with echo, things get even more messed up, as in some
> versions of echo, \ is an escape as well, and even if the shell
> you are using leaves the trailing \ intact, there is no guarantee
> that echo will, so even echo \\ is not necessarily going to produce
> a \ on stdout (there is no portable way using echo).
>
> Just avoid this kind of thing (and use printf instead of echo).
>
> kre
>


It occurs to me that the -r option of read is related.


Re: Incorrect alias expansion within command substitution

2022-02-03 Thread Dennis Williamson
On Thu, Feb 3, 2022, 11:14 AM Alex fxmbsw7 Ratchev 
wrote:

> aliases are the way not to write duplicate code
>
>


No, functions are.

>


Re: some unknown bug, says : command not found

2021-11-01 Thread Dennis Williamson
On Mon, Nov 1, 2021, 3:46 PM Greg Wooledge  wrote:

> On Tue, Nov 02, 2021 at 03:23:15AM +0700, Robert Elz wrote:
> > Date:Mon, 1 Nov 2021 12:03:48 -0400
> > From:Greg Wooledge 
> > Message-ID:  
> >
> >   | > bash: : command not found
> >   | > bash: : command not found
> >   |
> >   | Because this is you, I can't be sure whether you are correctly
> pasting
> >   | the output from your terminal into email,
> >
> > Actually, because it is him, it is more likely that he has "cat" aliased
> > to ' ' somehow, since he loves aliases so much.
>
> Not a bad guess, but I can't reproduce it that way:
>
> unicorn:~$ bash
> unicorn:~$ alias cat=' '
> unicorn:~$ cat /dev/null
> bash: /dev/null: Permission denied
> unicorn:~$ alias cat=''
> unicorn:~$ cat /dev/null
> bash: /dev/null: Permission denied
>
> Then I tried with a non-breaking space, and that's closer, but
>
> unicorn:~$ alias cat=' '
> unicorn:~$ cat /dev/null
> bash:   : command not found
>
> The "space nbsp space" in that result is interesting, but I don't think
> that's what he's doing, even accounting for the possiblity that he
> typed one space where the terminal shows three.
>


I only get a non-breaking space and a space between the colons rather than
three space characters.

>


Re: bash git commands ( for noobs like me )

2021-10-22 Thread Dennis Williamson
On Fri, Oct 22, 2021, 8:53 PM Alex fxmbsw7 Ratchev 
wrote:

> could someone share some git wisdom
> in preciese few and similiar commands
>
> show version ( of .git url )
> show available versions
> git update tree [ to specific release / version, or newest ]
>

I'm sure there are lists that provide git support. But when I have a git
question the Great and Powerful Google provides the answers I need (pay no
attention to the man behind the curtain).

>


Re: Misleading error when attempting to run foreign executable

2021-10-04 Thread Dennis Williamson
On Mon, Oct 4, 2021, 9:09 AM Ilkka Virta  wrote:

> On Mon, Oct 4, 2021 at 4:46 PM Chet Ramey  wrote:
>
> > Bash reports the error it gets back from execve. In this case, it's
> > probably that the loader specified for the executable isn't present on
> your
> > system.
> >
>
> OTOH, for a script, Bash checks to see if the problem is with the
> interpreter and reports accordingly:
>
>  $ ./foo.sh
> bash: ./foo.sh: /bin/noexist: bad interpreter: No such file or directory
>
> The shell does go on to stat() the file after getting ENOENT from execve(),
> so I suppose it could
> add some clarifying note to the error message for the case of a binary file
> too.
>

The error is produced by the kernel. Bash merely passes it along.

>


Re: help for needs to mention for ((...))

2021-09-19 Thread Dennis Williamson
On Sun, Sep 19, 2021, 4:07 PM Lawrence Velázquez  wrote:

> On Sun, Sep 19, 2021, at 3:25 PM, 積丹尼 Dan Jacobson wrote:
> > $ help for
> > only mentions
> >for name [ [ in [ word ... ] ] ; ] do list ; done
> > and needs to be updated to mention
> >for (( expr1 ; expr2 ; expr3 )) ; do list ; done
>
> Not particularly intuitive, but:
>
> bash-5.1$ help 'for (('
> for ((: for (( exp1; exp2; exp3 )); do COMMANDS; done
> Arithmetic for loop.
>
> Equivalent to
> (( EXP1 ))
> while (( EXP2 )); do
> COMMANDS
> (( EXP3 ))
> done
> EXP1, EXP2, and EXP3 are arithmetic expressions.  If any expression is
> omitted, it behaves as if it evaluates to 1.
>
> Exit Status:
> Returns the status of the last command executed.
>
> --
> vq
>


And

help 'for*'

(No space) gets them both.

>


Re: Interactive commands cant be backgrounded if run from bashrc

2021-09-01 Thread Dennis Williamson
On Wed, Sep 1, 2021, 8:42 PM Greg Wooledge  wrote:

> On Wed, Sep 01, 2021 at 09:37:02PM -0400, Dale R. Worley wrote:
> > "C. Yang"  writes:
> > > emacs test.txt &
> > >
> > > fg
> >
> > > bash: fg: no job control
>
> > It sounds like Bash doesn't activate the job-control features until
> > .bashrc is completed.
>
> Well, there's an easy fix for that.  Just put "set -m" before the
> last two commands.
>
> I tested with "set -m" and "vim & fg" just now, and it appeared to work.
>
>


Do processes started in .bashrc have a terminal? I would suspect that
something without a try would either complain or work differently. I'll
have to play around with it.


Re: parameter expansion with `:` does not work

2021-07-07 Thread Dennis Williamson
On Wed, Jul 7, 2021, 7:55 PM  wrote:

>
>
> Things are clearer now.
>
>
>
> > Seriously, just replace the :- expansion with := and go on with your
> code.
> > It's the least intrusive change, and won't disturb your logic.
>
>
>
>  I executed
>
>
>
> echo "${parameter:-word}"; echo "${parameter}"
>
>
>
> and then
>
>
>
> echo "${parameter:=word}"; echo "${parameter}"
>
>
>
> It was to make the distinction clear.
>
>
>
> As I was in it, have also changed
>
>
>
> fdir=${fdir:-$PWD}
>
>
>
> to
>
>
>
> fdir=${fdir:=$PWD}
>
>
>
>


Ack!


Re: parameter expansion with `:` does not work

2021-07-07 Thread Dennis Williamson
On Wed, Jul 7, 2021, 4:50 PM  wrote:

>
> Have noticed that parameter expansion with `:` does not work
>
>
>
> : ${fltype:-"texi,org"}  # alternative to `fltype=`
>
>


$ unset foo
$ : ${foo:-bar}
$ echo "$foo"

$ : ${foo:=bar}
$ echo "$foo"
bar

The first form is a substitution and the second form is an assignment.


Re: Changing the way bash expands associative array subscripts

2021-04-06 Thread Dennis Williamson
On Tue, Apr 6, 2021, 3:09 PM Greg Wooledge  wrote:

> On Wed, Apr 07, 2021 at 03:53:43AM +0800, konsolebox wrote:
> > Also if Bash could just store associative array
> > values as a list to preserve store order and stop expanding
> > "${array[@]}" based on the sorted order of the keys, then the slice
> > function can also be applied there.
>
> There is no sorting in the output.  The keys come out in an order that
> only makes sense to the little gerbils inside bash, not to us humans.
> This is common with hash tables, and the same thing happens with python's
> dictionaries, perl's hashes, and tcl's arrays (but not tcl's dictionaries,
> which are closer to what you're envisioning).
>
> unicorn:~$ perl -e 'use Data::Dumper; %hash=qw(a b c d e f g h); print
> Dumper(\%hash);'
> $VAR1 = {
>   'e' => 'f',
>   'g' => 'h',
>   'c' => 'd',
>   'a' => 'b'
> };
>
> unicorn:~$ tclsh <<'EOF'
> array set hash {a b c d e f g h}; puts [array names hash]
> EOF
> e a g c
>

Python 3.7 has insertion-order dictionaries. So these are dependable
gerbils.

>


Re: Likely Bash bug

2021-03-16 Thread Dennis Williamson
.

On Tue, Mar 16, 2021, 10:22 PM Lawrence Velázquez  wrote:

> > On Mar 16, 2021, at 11:08 PM, Dennis Williamson <
> dennistwilliam...@gmail.com> wrote:
> >
> > I've been playing with your optimized code changing the read to grab data
> > in chunks like some of the other optimized code does - thus extending
> your
> > move from by-word to by-line reading to reading a specified larger number
> > of characters.
> >
> > IFS= read -r -N 4096 var
> >
> > And appending the result of a regular read to end at a newline. This
> seemed
> > to cut about 20% off the time. But I get different counts than your code.
> > I've tried using read without specifying a variable and using the
> resulting
> > $REPLY to preserve whitespace but the counts still didn't match.
> >
> > In any case this points to larger chunks being more efficient.
>
> Wrong thread?
>
> vq


Oops


Re: Likely Bash bug

2021-03-16 Thread Dennis Williamson
On Tue, Mar 16, 2021, 6:19 PM Lawrence Velázquez  wrote:

> > On Mar 16, 2021, at 6:01 PM, Jay via Bug reports for the GNU Bourne
> Again SHell  wrote:
> >
> >   Hello,
> >
> >   I have been using/exploring Linux for ~ 2yrs; have corrupted a couple
> >   systems more than once either through their instability with libraries
> >   or just excess stress.
> >
> >   I don't consider current case to be either of the above; see attached.
> >
> >   The system is modern Intel computer, 2018 to 2019 configured in BIOS
> >   mode. Operating system is BionicPup64 8.0.
> >
> >   Best Regards.
> > 
>
> Reproduced below for anyone who doesn't feel like reading a bug
> report out of an RTF document.
>
> vq
>
>
>
> From: root
> To: bug-bash@gnu.org,b...@packages.debian.org
> Subject: [ash--bash interference (for reference)]
>
> Configuration Information [Automatically generated, do not change]:
> Machine: x86_64
> OS: linux-gnu
> Compiler: gcc
> Compilation CFLAGS:  -DPROGRAM='bash' -DCONF_HOSTTYPE='x86_64'
> -DCONF_OSTYPE='linux-gnu' -DCONF_MACHTYPE='x86_64-pc-linux-gnu'
> -DCONF_VENDOR='pc' -DLOCALEDIR='/usr/share/locale' -DPACKAGE='bash' -DSHELL
> -DHAVE_CONFIG_H   -I.  -I../. -I.././include -I.././lib  -Wdate-time
> -D_FORTIFY_SOURCE=2 -g -O2
> -fdebug-prefix-map=/build/bash-vEMnMR/bash-4.4.18=.
> -fstack-protector-strong -Wformat -Werror=format-security -Wall
> -Wno-parentheses -Wno-format-security
> uname output: Linux puppypc23046 4.19.23 #1 SMP Tue Feb 19 15:07:58 GMT
> 2019 x86_64 x86_64 x86_64 GNU/Linux
> Machine Type: x86_64-pc-linux-gnu
>
> Bash Version: 4.4
> Patch Level: 19
> Release Status: release
>
> Description:
> [Original ash executable/script reduced to 4 bytes after download
> of "Clonezilla"
> through Puppy Package Manager. Reboot of system hung at
> 'switching-layers'.]
>
> Repeat-By:
> [Believed occurred after an ash co-dependency download as part of
> install.]
>
> Fix:
> [Noted xwin errors relating to ash on shutdown; had backup
> savefile. Compared /bin and saw the difference. Replaced ash from backup
> file to working folder.]
>


I've been playing with your optimized code changing the read to grab data
in chunks like some of the other optimized code does - thus extending your
move from by-word to by-line reading to reading a specified larger number
of characters.

IFS= read -r -N 4096 var

And appending the result of a regular read to end at a newline. This seemed
to cut about 20% off the time. But I get different counts than your code.
I've tried using read without specifying a variable and using the resulting
$REPLY to preserve whitespace but the counts still didn't match.

In any case this points to larger chunks being more efficient.

>


Re: Undocumented feature: Unnamed fifo '<(:)'

2020-06-28 Thread Dennis Williamson
On Sun, Jun 28, 2020, 8:50 AM felix  wrote:

>
>_out=$(date -d "$_string" +%s)
> many time in same script, I run something like:
>
> _fifo=$(mktemp -u /tmp/fifo-)
> mkfifo $_fifo
> exec 9> >(exec stdbuf -o0 date -f - +%s >$_fifo 2>&1)
> exec 8<$_fifo
> rm $_fifo
>
> Then to convert human datetime to UNIX SECONDS:
>
> echo >&9 $_string
> read -t 1 -u 8 _out
>
>


How is running your

echo >&9 $_string
read -t 1 -u 8 _out

many times better than running your

   _out=$(date -d "$_string" +%s)

many times?

Why don't you just use a function?

date_to_epoch () {
date -d "$1" +%s
}

_out=$(date_to_epoch "$_string")


Re: Backspace echoed incorrectly with TERM=garbage

2020-06-18 Thread Dennis Williamson
On Thu, Jun 18, 2020, 6:03 PM Bryan Henderson 
wrote:

> ...

  Any ideas on how I could see
> the raw character stream sent to a terminal?
>
>


Try the xev program. It will show X events and may reveal the keypresses
you're interested in.

>


Re: Backspace echoed incorrectly with TERM=garbage

2020-06-17 Thread Dennis Williamson
On Wed, Jun 17, 2020, 5:07 PM  wrote:

> Configuration Information [Automatically generated, do not change]:
> Machine: x86_64
> OS: linux-gnu
> Compiler: gcc
> Compilation CFLAGS: -g -O2
> -fdebug-prefix-map=/build/bash-2bxm7h/bash-5.0=. -fstack-protector-strong
> -Wformat -Werror=format-security -Wall -Wno-parentheses -Wno-format-security
> uname output: Linux rhino.giraffe-data.com 4.19.0-9-amd64 #1 SMP Debian
> 4.19.118-2+deb10u1 (2020-06-07) x86_64 GNU/Linux
> Machine Type: x86_64-pc-linux-gnu
>
> Bash Version: 5.0
> Patch Level: 3
> Release Status: release
>
> Description:
>
>   With TERM environment variable set to an undefined terminal type, Bash
>   echoes a backspace as a space; I expect it to echo as a backspace
> (ctl-h).
>   It edits the line properly; it just isn't displayed correctly.
>
>   Other line editing functions have the same problem.
>
>   Setting TERM from the Bash prompt (to anything) puts things back to
> normal.
>
>   It worked (Backspace echoes as a ctl-H backspace character) in an earlier
>   version of Bash (don't know which one), but not in 5.0.3(1) from Debian
> or
>   5.1 from ftp.gnu.org.
>
> Repeat-By:
>
>   $ TERM=nosuchterm bash --norc
>
>   At the prompt, type the 7 keystrokes
>
> l s q q BS BS CR
>
>   It echoes
>
> l s q q SP SP CR LF
>
>   and performs an 'ls' command, showing that the line was properly edited.
>
>


I imagine that depends on your terminal and your stty settings. On MacOS
with Bash 5 in Terminal.app what you describe doesn't happen for me. What
terminal are you using? What is the output of stty -a with respect to
erase? What do you get in that setup when you press Ctrl-V then Backspace?


Re: No way to 'bind -x' symbolic character names

2019-11-30 Thread Dennis Williamson
On Sat, Nov 30, 2019, 11:24 AM Chet Ramey  wrote:

>
Readline binds the terminal special characters if the variable
> `bind-tty-special-chars' is set, and it's set by default.
>

Wow, that's been in Bash a long time and I never noticed it! Thanks!

>


Re: No way to 'bind -x' symbolic character names

2019-11-30 Thread Dennis Williamson
On Fri, Nov 29, 2019, 10:40 AM Nikolaos Kakouros  wrote:

> Using bash version:
>
> GNU bash, version 5.0.11(1)-release (x86_64-pc-linux-gnu)
>
>
> Trying to map Backspace to execute a function, I try to do:
>
> bind -x '"Rubout": my_func'
>
> This, as expected, binds the string 'Rubout' to the function. Omitting the
> double quotes makes bind fail. Escaping, like `\Rubout`, works neither.
>
> This is important in the case of Backspace, as there is no (to my
> knowledge) other way to bind the backspace than using Rubout. Using Konsole
> as my terminal emulator, `C-v Backspace` prints `^?` which I haven't
> managed to use with bind.
>

Backspace is a terminal setting which has precedence. You have to first
undefine it.

stty erase undef
bind -x '"\C-?":my_func'

>


Re: [readline] Multibyte invisible chars cause weird prompt length calculation issue

2019-11-26 Thread Dennis Williamson
On Tue, Nov 26, 2019, 9:50 AM Алексей Шилин  wrote:

> В Вт, 26/11/2019 в 07:35 -0600, Dennis Williamson пишет:
> > You have printable characters enclosed. For example, \u. _Each_
> > sequence of unprintable characters needs to be separately enclosed
> > _without_ enclosing the printable ones.
> >
> > The first part of your prompt is what needs to be corrected. The
> > latter part after "debian_chroot" is correct.
>
> Ah, you meant that it should be:
>
> PS1='\[\e]0;\]\u@\h:\w\[\a\]${debian_chroot:+($debian_chroot)}\[\033[01
> ;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '
>
> Or the ']0;' part should be outside of '\[...\]', too?
>

No. As Greg pointed out, I missed the fact that the strings were part of
the escape sequence for the terminal title. Sorry for the confusion.

>


Re: [readline] Multibyte invisible chars cause weird prompt length calculation issue

2019-11-26 Thread Dennis Williamson
On Tue, Nov 26, 2019, 5:46 AM Алексей Шилин  wrote:

> В Пн, 25/11/2019 в 18:29 -0800, L A Walsh пишет:
> > Multi-byte or not, invisible characters need to be enclosed
> > as documented under 'PROMPTING':
> >
> >  \[ begin a sequence of non-printing characters, which  could
> > be  used  to  embed  a terminal control sequence into the
> > prompt
> >  \] end a sequence of non-printing characters
> >
>
> I know that.
>
> And they *are* enclosed: PS1='\[\e]0;\u@\h: \w\a\]${debian_chroot...
>   ^~^~
>
> As expected, they are not being printed -- but for some reason lead to
> the described issue.
>
>

You have printable characters enclosed. For example, \u. _Each_ sequence of
unprintable characters needs to be separately enclosed _without_ enclosing
the printable ones.

The first part of your prompt is what needs to be corrected. The latter
part after "debian_chroot" is correct.

>


Re: Seg history

2019-10-22 Thread Dennis Williamson
On Tue, Oct 22, 2019, 8:10 AM younes berramdane 
wrote:

> Hello,
> I have found a seg in the history of bash while I was doing a project for
> my school,
> (Put fc -s at the last command of the history file [~/.sh_history] for
> bash posix or [~/.bash_history] for bash then launch bash and execute fc -s
> again)
>
> Best regards,
> Younes Berramdane.
>

This causes fc -s to re-execute itself in a tight loop repeatedly until a
seg fault occurs.

I don't know whether Bash should catch this but it definitely falls under
"doctor, it hurts when I do this" - IOW, don't do that. Especially since it
takes extra effort to set up the necessary conditions.


Re: alias problem -- conflict found

2019-07-12 Thread Dennis Williamson
On Fri, Jul 12, 2019, 3:46 PM L A Walsh  wrote:

> On 2019/07/12 11:51, Eli Schwartz wrote:
>
>
> find_cmds() {
>   for c in "$@"; do
> type -P $c >&/dev/null || {
>   Pe "$0#$LINENO: Cannot find %s", "$c"
>   exit 1; }
> alias $c=$(type -P $c);
>   done
> }
>
>
>

This is a perfect example. I have to guess what Pe is. I presume it means
Print_error. If so, that's what it should be named - for readability. And
instead of assuming that it's a function, I have to hope it's not an alias.
By the way, why isn't type -p aliases to Pathof or something?



>
> You claim that my saying the bash-builtins are a type of alias for an
> external command that it is intended to have some similar functionality
> to, is
> "nonsense".  To  that assertion, I used the fact that many or most bash
> builtins that replace external counterparts are also following some
> POSIX stated behavior to support my original assertion that they are
> intended to be drop-in
> replacements for those commands.  I.e. using the design requirements for
> those bash built-ins that replace external posix components, its easy to
> see
> that your nonsensical response of 'Nonsense' was incorrect.  Talking about
> different methods of saying the same thing, like aliasing is about as on
> topic as anything.
>
>


Baby Face Nelson is an alias for Lester Joseph Gillis. John Dillinger was a
contemporaneous bank robber but he was not an alias for Mr. Gillis (but
they did partner at one point). Perhaps Pretty Boy Floyd would make a
better example though since his nickname bears a similarity to Gillis'.

But I digress.



Ultimately one of the facts at issue is that Bash is both a scripting
language and a command line interface. As the latter, it includes a number
of command line conveniences that should not be used in scripts. Among
those, in my opinion, are aliases and tilde expansions. I would also
include the overuse of pipes. Of course they are fundamental to the Unix
way and hacking something together on a command line for a one off or while
feeling one's way toward a solution is fine. I'd better not see a script
containing grep piped into awk

As far as saving keystrokes while typing goes, any good editor can be a
great deal of help in this pursuit.


Re: built-in printf %f parameter format depend on LC_NUMERIC

2019-07-09 Thread Dennis Williamson
>From the bc man page on Ubuntu:

This version of bc was implemented from the POSIX P1003.2/D11 draft and
contains several differences and extensions rela‐
   tive  to the draft and traditional implementations.


and

LANG environment
  This  version  does  not  conform to the POSIX standard in
the processing of the LANG environment variable and all
  environment variables starting with LC_.


On Tue, Jul 9, 2019 at 1:29 PM Chet Ramey  wrote:

> On 7/9/19 11:26 AM, lea.g...@noiraude.net wrote:
>
> > Bash Version: 5.0
> > Patch Level: 3
> > Release Status: release
> >
> > Description:
> > When formatting floating point numbers in Bash's built-in
> > printf with %s, the argument format depends on the LC_NUMERIC
> > environment variable.
>
> As POSIX requires:
>
>
> http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap07.html#tag_07_03_04
>
> The `decimal_point' member of the LC_NUMERIC category defines the radix
> character in floating point numbers, for both input and output.
>
> > If the LC_NUMERIC language defines a comma , as decimal
> > separator, the built-in printf will not be able to recognize
> > floating-point numbers using a decimal point . as it is when
> > using the result of bc
>
> This depends on the behavior of strtold/strtod. POSIX requires strtod to
> honor the radix character as defined in LC_NUMERIC. Since LC_NUMERIC
> determines the radix character for input and output, it looks like `bc'
> is not POSIX conformant.
>
> --
> ``The lyf so short, the craft so long to lerne.'' - Chaucer
>  ``Ars longa, vita brevis'' - Hippocrates
> Chet Ramey, UTech, CWRUc...@case.eduhttp://tiswww.cwru.edu/~chet/
>
>

-- 
Visit serverfault.com to get your system administration questions answered.


Re: command "cat /etc/localtime" breaks output on tty-terminal

2019-06-23 Thread Dennis Williamson
On Sun, Jun 23, 2019, 7:18 AM bitfreak25  wrote:

> On Sun, 23 Jun 2019 06:04:29 -0500
> Dennis Williamson  wrote:
>
> > On Sun, Jun 23, 2019, 5:31 AM bitfreak25  wrote:
> >
> > > OS: Arch Linux 5.1.12-arch1-1-ARCH (tty1)
> > > Bash-Version: 5.0.7(1)-release
> > > localization: de_DE.UTF-8 UTF-8
> > > keymap: de-latin1-nodeadkeys
> > >
> > > Description:
> > > The command "cat /etc/localtime" was called in a tty-terminal. After
> that
> > > some characters will be printed incorrectly (mostly "cyrillic" chars
> > > instead of the correct ones). The typed chars seems to be handled
> correctly
> > > (e.g. calling "exit") but the output is broken at this point. This
> > > behaviour is reproducible on my other PC with Debian Stable
> (Bash-Version
> > > in Debian: 4.4-5), so it seems to be a old bug. Changing to another
> tty or
> > > rebooting the OS will fix this behaviour until the command is called
> again.
> > >
> > > Kind regards,
> > > bitfreak
> > >
> > >
> >
> >
> > /etc/localtime is symlinked to a file that contains time zone data. If
> you
> > enter the command
> >
> > file -L /etc/localtime
> >
> > you'll see that that's the case. It contains data that's not meant to be
> > displayed including control characters which cause the effect you
> observed.
> > If you cat any so-called binary file such as this you are likely to see
> the
> > same kind of thing happen. Entering the
> >
> > reset
> >
> > command in the affected terminal will correct the problem after it
> occurs.
>
> I kind of thought that this could be the reason. It also happens with
> "cat /dev/urandom" which is stopped by [STRG] + [C].
>
> It seems to be a very small bug thats only breaks the output with an
> unusual command and there are already 3 workarounds. But in my opinion
> it should be fixed some time as it isn't the correct behaviour like
> doing it with a gui-terminal e.g. xfce4-terminal.
>
> Kind regards,
> bitfreak
>


It's not a bug. It's expected behavior. If a useful sequence of control
characters is output - useful things happen. If you take that away then
lots of stuff doesn't work.

Solution? Don't cat non-text files to the terminal.

>


Re: command "cat /etc/localtime" breaks output on tty-terminal

2019-06-23 Thread Dennis Williamson
On Sun, Jun 23, 2019, 5:31 AM bitfreak25  wrote:

> OS: Arch Linux 5.1.12-arch1-1-ARCH (tty1)
> Bash-Version: 5.0.7(1)-release
> localization: de_DE.UTF-8 UTF-8
> keymap: de-latin1-nodeadkeys
>
> Description:
> The command "cat /etc/localtime" was called in a tty-terminal. After that
> some characters will be printed incorrectly (mostly "cyrillic" chars
> instead of the correct ones). The typed chars seems to be handled correctly
> (e.g. calling "exit") but the output is broken at this point. This
> behaviour is reproducible on my other PC with Debian Stable (Bash-Version
> in Debian: 4.4-5), so it seems to be a old bug. Changing to another tty or
> rebooting the OS will fix this behaviour until the command is called again.
>
> Kind regards,
> bitfreak
>
>


/etc/localtime is symlinked to a file that contains time zone data. If you
enter the command

file -L /etc/localtime

you'll see that that's the case. It contains data that's not meant to be
displayed including control characters which cause the effect you observed.
If you cat any so-called binary file such as this you are likely to see the
same kind of thing happen. Entering the

reset

command in the affected terminal will correct the problem after it occurs.


Re: readline: How to unbind _all_ keys

2019-05-21 Thread Dennis Williamson
On Tue, May 21, 2019 at 3:04 AM Henning  wrote:

> On 20/05/2019 15:38, Chet Ramey wrote:
> > On 5/19/19 10:43 AM, Henning wrote:
> >> I don't like to have dozens of key bindings I never use. Currently I
> >> am issuing lots of lots of bind -r/-u commands to get rid of the
> >> default bindings. This slows down console startup unnecessarily.
> >>
> >> I would really like to have an inputrc command like $removeall or
> >> something like bind -r/-u all.
> >> Or is there something undocumented for this purpose?
> >
> > There is not, and I don't see much point to adding one. If you want to
> > remove the bindings for all keys, something like this should work:
>
> Sorry, the subject of my mail should have been "... all non-self-insert
> kes.
>
> >
> > for ((f=0; f < 256; f++ ))
> > do
> >   bind -r \\$(printf "%03o" $f)
> > done
> >
>
> smiling ...
>
> The following variant does what I want:
>
> K=( ' ' ! '\"' \# $ % \& \' \( \) \*  +   ,   -  .  /
>  0  1   2   3 4 5  6  7  8  9  : \;  \<   = \> \?
>  @  A   B   C D E  F  G  H  I  J  K   L   M  N  O
>  P  Q   R   S T U  V  W  X  Y  Z \[ '\\' \]  ^  _
> \`  a   b   c d e  f  g  h  i  j  k   l   m  n  o
>  p  q   r   s t u  v  w  x  y  z \{  \|  \} \~ )
>
> for ((k=0; k<95; k++)); do
> bind -r "\e${K[k]}"
> bind -r "\e\C-${K[k]}"
> bind -r "\C-x\C-${K[k]}"
> bind -r "\C-x${K[k]}"
> bind -r "\C-${K[k]}"
> done
>
> for k in O{A,B,C,D,H,F} \\e [200; do
> bind -r "\e$k"
> done
>
> bind -f /0/e/inputrc
>
> unset k K
>
> But this means nearly 500 bind -r commands. And that was the reason for
> my original mail, the question, if there is a less expensive way to get
> what I want.
>
> And another problem: after removing all \C-x sequences I used bind -x
> to bind a shell command to \C-x proper. The result, when hitting \C-x,
> is the following error message:
>
> bash_execute_unix_command: cannot find keymap for command
>
> Using a sequence other than \C-x works as expected.
> My guess is that \C-x can't be used alone. And that this can only be
> changed in the source code.
>
> Henning
>
>
>
Why don't you unbind the keystrokes that are actually bound?

while read -r b; do bind -r "$b"; done < <(bind -p | awk -F ':' '/./
&& !/self-insert|accept-line|^#/ {gsub("\"", "", $1); print $1}')

On my system, that takes 0.011 seconds to run and it's not iterating
through a bunch of key sequences that aren't there.

It does seem to leave behind a few, some of which match cchars (control
characters) in stty -a

"\C-?": backward-delete-char
"\C-v": quoted-insert
"\C-@": set-mark
"\e ": set-mark
"\C-u": unix-line-discard
"\C-w": unix-word-rubout

I haven't made any effort to troubleshoot that.

As an alternative, just put all the (un)bindings in ~/.inputrc, for example:

"\C-s": ""

To automate that:

bind -p | awk -F ':' '/./ && !/self-insert|accept-line|^#/ {print $1 ":
\"\""}' >> ~/.inputrc

Run that once from a shell with all the default bindings in place, edit the
file to remove any that conflict with your own custom bindings and you're
done. There will still be a small shell startup time cost, but I'm betting
it's very small.

Frankly, I'd have to dislike key bindings A LOT to go to the trouble of
doing all this unbinding.

> But I can not remove bindings with key-sequences my terminal does not
produce like \eO[ABCDFH]

But then you show a script that purports to do exactly that.

This inquiry would have been better suited for help-bash rather than
bug-bash.

-- 
Visit serverfault.com to get your system administration questions answered.


Re: Handling of Zero-Width escapes in PS1

2019-05-04 Thread Dennis Williamson
On Sat, May 4, 2019, 3:39 PM  wrote:

> Configuration Information [Automatically generated, do not change]:
> Machine: x86_64
> OS: linux-gnu
> Compiler: gcc
> Compilation CFLAGS:  -DPROGRAM='bash' -DCONF_HOSTTYPE='x86_64'
> -DCONF_OSTYPE='linux-gnu' -DCONF_MACHTYPE='x86_64-pc-linux-gnu'
> -DCONF_VENDOR='pc' -DLOCALEDIR='/usr/share/locale' -DPACKAGE='bash' -DSHELL
> -DHAVE_CONFIG_H   -I.  -I../. -I.././include -I.././lib  -Wdate-time
> -D_FORTIFY_SOURCE=2 -g -O2
> -fdebug-prefix-map=/build/bash-vEMnMR/bash-4.4.18=.
> -fstack-protector-strong -Wformat -Werror=format-security -Wall
> -Wno-parentheses -Wno-format-security
> uname output: Linux desktop 5.0.3-050003-generic #201903191333 SMP Tue Mar
> 19 13:35:24 UTC 2019 x86_64 x86_64 x86_64 GNU/Linux
> Machine Type: x86_64-pc-linux-gnu
>
> Bash Version: 4.4
> Patch Level: 19
> Release Status: release
>
> Description:
> When setting up a complex PS1 prompt where parts of the
> prompt is expanded on every new prompt displayed by bash
> the escape sequences that are generated by that dynamic
> part are handled improperly (read: not at all).
>
> The desired behaviour should treat such escapes for e.g.
> the sequences \[ and \] equal both when the prompt expands
> to stuff\[stuff\]stuff, regardless of whether this was
> reached by "stuff$(echo \[stuff\])stuff" (\[\] handled) or
> reached by 'stuff$(echo \[stuff\])stuff' (not handled) being
> set as the value of PS1.
>
> Repeat-By:
> To demonstrate this odd behaviour assume some command
> that displays changing information at each invokation:
>
> __test1(){ echo -e "Random is \\[\e[37;1m\\]$RANDOM\e[0m"; }
>
> Now let's assume two cases:
>
> Case 1:
> PS1='Test$(__test1)Test\[\e[0m\]$ '
> -> Shows \[\] markers, includes output of $(__test1) dynamically
>
> Case 2:
> PS1="Test$(__test1)Test\[\e[0m\]$ "
> -> Displays correct, but statically includes output of $(__test1)
>
> The desired behaviour is dynamic inclusion of $(__test1) as with
> case 1 while having the \[\] markers respected as seen in case 2.
>
> Splitting the output of __test1 to separate sections with
> \[\] markers and such which don't need them is not possible,
> as the number of such sections may vary and the limited syntax
> of PS1 does not allow for loops and other conditional constructs
> on its top level.
>
> Also leaving out the \[\] markers from __test1 will cause the
> displayed prompt to misbehave.
>
> Fix:
> Move handling of \[ and \] markers to be done on the fully
> expanded, representation of the PS1 variable after variable
> substitutions and subshell output have been inserted.
>

I compute complex strings and assign PS1 within PROMPT_COMMAND rather than
expecting PS1's promptvars command substitution to do that - since
backslash escapes are done earlier. See "PROMPTING" in the man page where
the order of processing is described.

>
>


Re: info missing in output of declare -a in 4.4.x

2019-02-17 Thread Dennis Williamson
On Sun, Feb 17, 2019, 6:01 PM L A Walsh 
>
> On 2/17/2019 2:19 PM, Dennis Williamson wrote:
> >
> > So it really is a bug of some sort, not that I use BASH ALIASES
> > for anything.  Was going to, but ...  and you're right, lots of
> > things aren't showing there.
> >
> >
> >
> >
> > Have you tried starting Bash without any startup files, creating an
> > alias and then checking the array?
> yes.  Just now.
> out of 14 vars starting with BASH
> only BASHOPTS is different in the clean startup.
> In a 'normal'[?] startup, there are 3 extra vars starting with BASH_:
>
> BASH_COMPLETION_COMPAT_DIR
> BASH_ENV (I set this, but unset it for this test)
> BASH_REMATCH
>
> then bash (type -p says /bin/bash)
>  --noprofile --norc
>
> Version would be same, and the debug related would be blank, but
> hmmm
> declare -A BASH_CMDS=()  (command hashing?)
>
> most of the BASH vars show no value (exception of
> version-related, BASH=/bin/bash & "BASHOPTS", but they
> DO have a value.  If I print it in the shell instead
> of using declare -p I see stuff.
>
>
>
>
>
>
>
>


Oh, interesting! In Bash 4 and 5, I just did declare -p with no args and it
showed BASH_ALIASES empty. But with declare -p BASH_ALIASES it shows the
contents (as does the alias command).

Other arrays that show this difference for me:

BASH_CMDS
DIRSTACK
GROUPS

Scalars that exhibit this issue:

BASHPID
BASH_COMMAND
BASH_SUBSHELL
COMP_WORDBREAKS
HISTCMD
LINENO
RANDOM
SECONDS


Re: info missing in output of declare -a in 4.4.x

2019-02-17 Thread Dennis Williamson
On Sun, Feb 17, 2019, 3:10 PM L A Walsh 
>
> On 2/16/2019 4:57 AM, Robert Elz wrote:
> > Date:Fri, 15 Feb 2019 22:21:25 -0800
> > From:L A Walsh 
> > Message-ID:  <5c67abe5.1030...@tlinx.org>
> >
> >   | Thought about thatrestarted a fresh shell.  Same same.
> >   | At least I know it's supposed to...
> >
> > It isn't just BASH_ALIASES - you'll see the same from lots of
> > other dynamic variables.
> >
> ---
> Woe!  That's what threw me -- it says empty, but it isn't.
> > Try actually accessing an element, as in ...
> >
> >
> > On occasion, the output from declare will show all the
> > aliases in BASH_ALIASES but I have no idea what sequence of
> > commands, of state of the universe, causes that to happen.
> >
> -
>
> AND -- just did it now, it doesn't even show BASH_ALIASES, but
> I know I have aliases defined.  Weird!
>
> So it really is a bug of some sort, not that I use BASH ALIASES
> for anything.  Was going to, but ...  and you're right, lots of
> things aren't showing there.
>
>
>

Have you tried starting Bash without any startup files, creating an alias
and then checking the array?

>


Re: in bash 4.4.12,want to verify a behavior...

2019-02-15 Thread Dennis Williamson
On Fri, Feb 15, 2019, 10:46 PM L A Walsh 
> I printed the various declares using:
>
> declare -p |& more
>
> One of the early entries is:
>
> declare -A BASH_ALIASES=()
>
> Yet if I type 'alias |& wc, I see 56 lines starting with alias.
>
> I _thought_ BASH_ALIASES was suppose to hold the aliases
> and for an "alias whence='type -a'", I should see something like
> declare -A BASH_ALIASES=([whence]='type -a ...) instead of
> the empty assignment above.
>
> Am I misunderstanding or missing something?
>
> I'm assuming ("guessing?") that other people see
> their aliases in
> BASH_ALIASES?
>
> Am trying to figure out where I should start looking for why
> this isn't set, but wanted to make sure my understanding of
> of this feature was correct.
>
> Thanks!
> -linda
>
>
>
>

It's likely that somewhere your BASH_ALIASES has been unset. See the manual
section quoted here:

BASH_ALIASES

An associative array variable whose members correspond to the internal list
of aliases as maintained by the alias builtin. (see Bourne Shell Builtins
).
Elements added to this array appear in the alias list; however, unsetting
array elements currently does not cause aliases to be removed from the
alias list. If BASH_ALIASES is unset, it loses its special properties, even
if it is subsequently reset.

>


Re: UUID as Array Keys strangely not possible

2019-01-25 Thread Dennis Williamson
On Fri, Jan 25, 2019, 9:51 PM Robert White  On 1/22/19 10:23 PM, Chet Ramey wrote:
> > On 1/22/19 3:32 PM, Robert White wrote:
> >> Howdy,
> >>
> >> The following cannot work because, for some reason, the array subscript
> >> parser insists on doing math on array indices even when the array is
> >> associative instead of numeric
> >>
> >> typeset -A UUID_TABLE
> >> ...
> >> UUID_TABLE+=( [${SOME_UUID}]=${SOME_VALUE} )
> >> ...
> >> some_command ${UUID_TABLE[${SOME_UUID}]}
> >>
> >> The parser and evaluator insist on doing math on ${SOME_UUID} no matter
> how
> >> its quoted or whatever. This seems extremely wrong.
> >
> > Do you have some sample UUID data to test this with?
> >
> I'm going to have to provisionally withdraw this report. The problem
> only seems to happen in the custom /init script in my initramfs. Trying
> to recreate it with a simpler script (and the same bash binary) on a
> fully running system using the the UUIDs I collected with blkid doesn't
> have a problem at all. So something "mysterious" is going on.
>
> The initscript is part of https://sourceforge.net/projects/underdog/ (if
> you care) and is part of my attempt to build a concordance of UUID to
> device to manager (e.g. lvm vs mdadm vs whatever) app. It works well
> except when it doesn't.
>
> Thanks for the prompt response. If I isolate the test case or the issue
> in general I'll be back. Even just to say never mind if I find a super
> stupid mistake. 8-)
>
> --Rob White.
>

I'm not going to try to do a full code review. It took me more time than I
was willing to spend already to find a file that has an associative array
referring to UUIDs in the first place and to put this message together.

Here are a few comments about prototype/init:

In the global scope UUID_TABLE is declared as an indexed array at one point
then an associative array later.

In the get_ (something) function an array element is set violating
separation of get and set.

In that same function, a max_index variable is set to the highest index of
a numeric array then the array is iterated using a C-style for loop. Arrays
in Bash are sparse and the correct way to iterate is to step over the
elements or the indices.

for element in "${array[@]}"

for index in "${!array[@]}"

But it seems you just want to add an element.

array+=(element)

There is a variable called AA. I didn't look to see if that means something
but I shouldn't have to. A better name is needed.

Forgive me if I misunderstood anything. It was just a cursory once over.

 Also, I didn't immediately notice what the UUID indexing problem initially
reported is caused by. Except that I played with an indexed array with a
UUID-like index. In that case the index *is* evaluated mathematically so
this may be your problem. That makes sense based on the redefinition I
mentioned above since the second declare will produce an error without
affecting the array.

>


Re: weird insert of backslashes in strings

2019-01-08 Thread Dennis Williamson
On Tue, Jan 8, 2019, 3:10 PM  Configuration Information [Automatically generated, do not change]:
> Machine: i686
> OS: linux-gnu
> Compiler: gcc
> Compilation CFLAGS: -fstack-protector -Wno-parentheses -Wno-format-security
> uname output: Linux bongo 2.6.32-042stab134.8 #1 SMP Fri Dec 7 17:16:09
> MSK 2018 i686 i686 i386 GNU/Linux
> Machine Type: i686-pc-linux-gnu
>
> Bash Version: 5.0
> Patch Level: 0
> Release Status: release
>
> Description:
> This script "weirdbackslashes":
>
> $ cat weirdbackslashes
> #===begin
> PRE='\/'
> echo 'define'${PRE}'\
> /'
> #===end
>
> produces with bash4:
> $ bash weirdbackslashes
> define\/\
> /
>
> and with bash5:
> $ bash5 weirdbackslashes
> \d\e\f\i\n\e\/\\\
> /
>
> Repeat-By:
> see Description
>


Reproduced. By the way, double quoting the variable eliminated the problem.


Re: "return" should not continue script execution, even if used inappropriately

2019-01-06 Thread Dennis Williamson
On Sat, Jan 5, 2019, 4:05 PM Robert Hailey 
> To the most excellent bash maintainers:
>
> I have found, what I consider to be a bug, in the following version of
> bash:
> * bash-4.4.23-1.fc28.x86_64
>
> It is related to this error message:
> * "return: can only `return' from a function or sourced script"
>
> When used inappropriately (such as running a correctly-written script
> that was merely intended to be sourced rather than executed), the
> return statement does not cease execution, and "falls through" to
> continue executing the script beyond the point that the author of the
> script clearly indicated that it should cease into realms of arbitrary
> and unexpected code paths.
>
> Best wishes, kind regards, and heartfelt thank-you for your
> dedicated service to the community.
>
> --
> Robert Hailey
>


You should be able to protect yourself from this by detecting if a script
is not being sourced when it's intended that it must be and acting
accordingly.

You could also do the following if you want a script to work under either
condition:

return 2>&1 || exit

Or substitute another action for exit. Note that I'm ignoring possible
caveats.

>


Re: comment on RFE: 'shift'' [N] ARRAYNAME

2018-09-27 Thread Dennis Williamson
On Tue, Sep 25, 2018, 7:17 PM L A Walsh  wrote:

> It struck me as it might be convenient if 'shift' could take an optional
> arrayname as an argument.  Would that be possible or would it cause some
> incompatibility?
>
> i.e.
>
> >  set one two three four five
> >  dcl -a ARGV=("$@")
> >  shift ARGV
> >  echo "${ARGV[@]}"
> two three four five
> >  shift 2 ARGV
> four five
>
> I know it can be done with a function, but with more mess.
> I used (maybe there's a better way, but...):
>
> (in my lib file ArFuncs.shh, that I can include)
>
> [include stdalias]
> #[include Types] #if type-checking include Types+line below
> lshift () {
>   (($#)) || return 1
>   int nshift=1
>   if [[ $1 =~ ^[0-9]+$ ]]; then nshift=$1; shift;fi
>   #if ! isArr $1; then echo >&2 "Need arrayname"; return 1; fi
>   my ar=$1; shift
>   my h="$ar[@]"
>   set "${!h}"
>   shift $nshift
>   eval "${ar}=("$@")"
> }; export -f lshift
>
>
>
> "my" - What is this, Perl?

array_shift=2
arr=("${arr[@]:$array_shift}")

Done.


>


Re: weird bash5 bug with ``for i; do echo; done; echo in''

2018-03-24 Thread Dennis Williamson
On Sat, Mar 24, 2018, 12:23 PM Dennis Williamson <
dennistwilliam...@gmail.com> wrote:

>
>
> On Sat, Mar 24, 2018, 11:45 AM Clark Wang <dearv...@gmail.com> wrote:
>
>> Hi Chet,
>>
>> Today I compiled bash5 (using default configuration) from the devel branch
>> (f602026a0ce - commit bash-20180316 snapshot) on macOS and found it breaks
>> one of my rc files. After some time of debugging I have the following
>> minimal example to reproduce the problem:
>>
>> $ bash5 -c 'for i; do echo; done; echo in'
>> bash5: -c: line 0: syntax error near unexpected token `in'
>> bash5: -c: line 0: `for i; do echo; done; echo in'
>> $
>>
>> Please take a look.
>>
>> -clark
>>
>
> Confirmed on macOS Sierra and Ubuntu 17.10.
>

bash5 -c 'for i; do echo in; done'

fails in the same way.

>


Re: weird bash5 bug with ``for i; do echo; done; echo in''

2018-03-24 Thread Dennis Williamson
On Sat, Mar 24, 2018, 11:45 AM Clark Wang  wrote:

> Hi Chet,
>
> Today I compiled bash5 (using default configuration) from the devel branch
> (f602026a0ce - commit bash-20180316 snapshot) on macOS and found it breaks
> one of my rc files. After some time of debugging I have the following
> minimal example to reproduce the problem:
>
> $ bash5 -c 'for i; do echo; done; echo in'
> bash5: -c: line 0: syntax error near unexpected token `in'
> bash5: -c: line 0: `for i; do echo; done; echo in'
> $
>
> Please take a look.
>
> -clark
>

Confirmed on macOS Sierra and Ubuntu 17.10.

>


Re: help shopt: mention what happens if only optnames are given

2017-11-05 Thread Dennis Williamson
On Nov 5, 2017 7:05 PM, "積丹尼 Dan Jacobson"  wrote:

$ help shopt
shopt: shopt [-pqsu] [-o] [optname ...]
Set and unset shell options.

Change the setting of each shell option OPTNAME.  Without any option
arguments, list all shell options with an indication of whether or not
each
is set.

Add:
If just optnames are given, list each's status.


It already says that. You quoted it.


Re: Bug? Explanation??

2016-12-30 Thread Dennis Williamson
On Dec 30, 2016 11:20 PM, "Peter & Kelly Passchier" <
peterke...@passchier.net> wrote:

Thanks Dennis and Grisha! I understand.

I had thought that every line that is piped into bash is it's own shell
alignment, but I understand it's more like sourcing, so these would be
more or less equivalent, right?

r=23; echo $r; echo -e 'r=bc\necho $r' >r; source r

r=23; echo $r; echo -e 'r=bc\necho $r' |bash

Thanks again,
Peter



Not really. You're sourcing into the current shell versus piping into a
subshell.

The line you pipe in is in the current shell until it's received by the
subshell. As a result it's subject to all the evaluation that can be
performed in the current shell. Once the child shell receives it the outer
quotes will already have been stripped and if there's additional evaluation
it will then be performed.


Re: possible in bash?: filter stderr of a prog & send filtered-output out on stderr leaving stdout untouched

2016-12-06 Thread Dennis Williamson
On Tue, Dec 6, 2016 at 4:09 PM, L A Walsh  wrote:

>
> Is there a way, in bash, to filter stderr and let the
> filtered result continue on stderr with the original
> stdout being output on stdout?
>
> with prog being the program to filter, and RE_filt being the
> filtering expression, conceptually, I wanted to do something
> like this:
>
> $prog >&3 2>&1 |grep -v "$RE_filt" >&2 3>&1
>
> (which of course doesn't work)
>
> Is it possible/doable?
>
> Tnx!
> -l
>
>
>
>
>
>
http://mywiki.wooledge.org/BashFAQ/047 (search for "stdout intact")






-- 
Visit serverfault.com to get your system administration questions answered.


Re: Could bash do what make does?

2016-11-28 Thread Dennis Williamson
On Sun, Nov 27, 2016 at 7:25 PM, Robert Durkacz 
wrote:

> Has thought been given, over the years, to extending bash to do
> what make does, in the obvious way that I am about to describe?
>
> It would be a matter of having chosen build commands do nothing if their
> outputs are newer than their inputs. For example that is, cc file.c -o
> file.o should execute normally if file.c is the newer file but do nothing
> if file.o is newer.
>
> Then you would have a deterministic script to build a system that simply
> skipped steps determined to be unnecessary.
>
> It is possible to achieve this without changing bash but it seems like
> there would be leverage in having bash deliberately support this mode.
>


Use the newer-than test:

source=file.c
object=file.o
[[ $source -nt $object ]] && cc "$source" -o "$object"


-- 
Visit serverfault.com to get your system administration questions answered.


Re: Unfamiliar; what does this do: "for file do"..."done"

2016-08-13 Thread Dennis Williamson
On Aug 13, 2016 6:36 AM, "L. A. Walsh"  wrote:
>
> I was looking at how the 'ldd' command(bash script) on my system and
> came across the code usage:
>
> for file do   ## about line 138 in my version
>  ...
>  case $file in
>  */* :
>  ;;
>  *) file=./$file
> ;;
>  esac
>  ...
> done
>
> It doesn't appear to set the value of file in any of the code
> above the 'for' statement, but is using it in the case statement
> just below the 'for' statement.
>
> As far as I can tell, nothing between the "do" and "done" is
> executed, which as far as I know, would seem to be expected
> behavior.  The 1st line of the file has:
>
> #! /bin/bash
>
> indicating bash (v. posix) semantics.
>
> Is there some shell construct that should make this work (execute),
> or is this "effectively" commenting this section out, though still
> processing quotes?
>
> Seems to have been this way for, the past several years leading me
> to think that the code path doesn't get used, or it's using
> some unknown bash functionality.
>
> It looks like it was intended to loop over program arguments left
> over after flag processing, but that's a guess based on the program
> structure.
>
> Any ideas?
>
> Tnx...
> Linda
>
>
>
>

There's an implied in "$@"

for file in "$@"


Re: readline doesn't refresh properly anymore

2016-06-02 Thread Dennis Williamson
On Jun 2, 2016 11:25 AM, "Charles T. Smith" 
wrote:
>
> Hello,
>
> I moved from ubuntu 10.04 to 14.04 and now readline usually doesn't
refresh
> my command line when scrolling through my history - the last tokens are
often
> not shown until I move the cursor there.  Is that due to a change in bash?
>
> TIA,
> cts
I'm guessing that you have non-printing characters in your prompt. I don't
know why the problem wouldn't have shown up for you before though if your
prompt hasn't changed. If this is the problem, you need to surround
sequences of non-printing characters with \[ and \].


bash 4.4-rc1 EXECIGNORE not fully working?

2016-03-19 Thread Dennis Williamson
$ type -a ls
ls is /bin/ls
$ # ls tab completion includes ls
$ ls foo
foo
$ EXECIGNORE=/bin/ls
$ type -a ls
bash: type: ls: not found
$ # ls tab completion does not include ls
$ ls foo
foo
$ /bin/ls foo
foo

So ls is still executed despite the setting. I tried the same with
/usr/bin/find and got the same result.

GNU bash, version 4.4.0(1)-rc1 (x86_64-unknown-linux-gnu)

-- 
Visit serverfault.com to get your system administration questions answered.


Re: Feature: Easily remove current command from history

2016-01-05 Thread Dennis Williamson
On Mon, Jan 4, 2016 at 4:35 PM, Dennis Williamson <
dennistwilliam...@gmail.com> wrote:

>
>
> On Mon, Jan 4, 2016 at 4:05 PM, Dennis Williamson <
> dennistwilliam...@gmail.com> wrote:
>
>>
>>
>> On Mon, Jan 4, 2016 at 3:07 PM, Eduardo A. Bustamante López <
>> dual...@gmail.com> wrote:
>>
>>> Take into account that many options have been provided (history -d, the
>>> space
>>> prefix, even editing .bash_history yourself).
>>>
>>> But you request a single key stroke to do this... why?
>>>
>>> If you enter a password by mistake in your shell, and it gets recorded,
>>> then
>>> you go and clean up. It's not hard to do.
>>>
>>> But since you request a simple-and-easy way of doing this, it seems like
>>> you do
>>> this a lot... which you shouldn't! :-)
>>>
>>> Now, it is up to you to convince Chet that it is so important to have a
>>> simple
>>> shortcut to do this. IMO, it isn't.
>>>
>>> --
>>> Eduardo Bustamante
>>> https://dualbus.me/
>>>
>>>
>>
>> Just bind your own keystroke to a function which uses history -d:
>>
>> histdel() {
>> local last_command histline
>>
>> last_command=$(history 1)
>>
>> histline="${last_command%  *}"
>>
>> history -d "$histline"#  I wish history -d accepted negative
>> offsets
>> }
>>
>> bind -x '"\ez": histdel'
>>
>> Then Esc-z or Alt-z will delete the most recent history entry. You could
>> choose another keystroke to bind.
>>
>>
>> --
>> Visit serverfault.com to get your system administration questions
>> answered.
>>
>
> Actually, this is better:
>
> histdel() {
>
> (#  use a subshell to make extglob setting and function variables
> local
>
> last_command=$(history 1)
>
> #  strip modified-entry marker, it doesn't matter if we delete an
> asterisk in the command since we're deleting it anyway
> last_command=${last_command/\*/ }
> shopt -s extglob
> last_command=${last_command##*( )}  # strip leading spaces
> histline="${last_command%%  *}"
>
> history -d "$histline"#  I wish history -d accepted negative
> offsets
>
> )
> }
>
> bind -x '"\ez": histdel'
>
> I'm using a subshell here. You can use the local keyword for variables and
> save and restore the extglob setting if you prefer.
>
> --
> Visit serverfault.com to get your system administration questions
> answered.
>


Petr Skočík pointed out to me in a private message that my subshell version
only affects the history within the subshell. Here is a version that
doesn't require setting extglob and is much shorter:

histdel () {
local histline commandline
IFS=' *' read -r histline commandline <<< "$(history 1)"
history -d "$histline"
}

-- 
Visit serverfault.com to get your system administration questions answered.


Re: Feature: Easily remove current command from history

2016-01-04 Thread Dennis Williamson
On Mon, Jan 4, 2016 at 3:07 PM, Eduardo A. Bustamante López <
dual...@gmail.com> wrote:

> Take into account that many options have been provided (history -d, the
> space
> prefix, even editing .bash_history yourself).
>
> But you request a single key stroke to do this... why?
>
> If you enter a password by mistake in your shell, and it gets recorded,
> then
> you go and clean up. It's not hard to do.
>
> But since you request a simple-and-easy way of doing this, it seems like
> you do
> this a lot... which you shouldn't! :-)
>
> Now, it is up to you to convince Chet that it is so important to have a
> simple
> shortcut to do this. IMO, it isn't.
>
> --
> Eduardo Bustamante
> https://dualbus.me/
>
>

Just bind your own keystroke to a function which uses history -d:

histdel() {
local last_command histline

last_command=$(history 1)

histline="${last_command%  *}"

history -d "$histline"#  I wish history -d accepted negative offsets
}

bind -x '"\ez": histdel'

Then Esc-z or Alt-z will delete the most recent history entry. You could
choose another keystroke to bind.


-- 
Visit serverfault.com to get your system administration questions answered.


Re: Feature: Easily remove current command from history

2016-01-04 Thread Dennis Williamson
On Mon, Jan 4, 2016 at 4:05 PM, Dennis Williamson <
dennistwilliam...@gmail.com> wrote:

>
>
> On Mon, Jan 4, 2016 at 3:07 PM, Eduardo A. Bustamante López <
> dual...@gmail.com> wrote:
>
>> Take into account that many options have been provided (history -d, the
>> space
>> prefix, even editing .bash_history yourself).
>>
>> But you request a single key stroke to do this... why?
>>
>> If you enter a password by mistake in your shell, and it gets recorded,
>> then
>> you go and clean up. It's not hard to do.
>>
>> But since you request a simple-and-easy way of doing this, it seems like
>> you do
>> this a lot... which you shouldn't! :-)
>>
>> Now, it is up to you to convince Chet that it is so important to have a
>> simple
>> shortcut to do this. IMO, it isn't.
>>
>> --
>> Eduardo Bustamante
>> https://dualbus.me/
>>
>>
>
> Just bind your own keystroke to a function which uses history -d:
>
> histdel() {
> local last_command histline
>
> last_command=$(history 1)
>
> histline="${last_command%  *}"
>
> history -d "$histline"#  I wish history -d accepted negative
> offsets
> }
>
> bind -x '"\ez": histdel'
>
> Then Esc-z or Alt-z will delete the most recent history entry. You could
> choose another keystroke to bind.
>
>
> --
> Visit serverfault.com to get your system administration questions
> answered.
>

Actually, this is better:

histdel() {

(#  use a subshell to make extglob setting and function variables
local

last_command=$(history 1)

#  strip modified-entry marker, it doesn't matter if we delete an
asterisk in the command since we're deleting it anyway
last_command=${last_command/\*/ }
shopt -s extglob
last_command=${last_command##*( )}  # strip leading spaces
histline="${last_command%%  *}"

history -d "$histline"#  I wish history -d accepted negative offsets

)
}

bind -x '"\ez": histdel'

I'm using a subshell here. You can use the local keyword for variables and
save and restore the extglob setting if you prefer.

-- 
Visit serverfault.com to get your system administration questions answered.


Re: Proposed Prompt Escapes

2015-11-17 Thread Dennis Williamson
On Tue, Nov 17, 2015 at 4:16 PM, Ángel González  wrote:

> While we are talking about new prompt escapes, I would love to be able
> to put in the prompt escapes elapsed time values from the previous
> command, so prefixing with time(1) could be redundant (if the intended
> resource was provided as an escape).
>
> Regards
>
>
Do you mean something like:

PS1='$SECONDS '

(along with shopt -o promptvars)

-- 
Visit serverfault.com to get your system administration questions answered.


Re: Possible bug in getopts when required argument is not supplied

2015-11-13 Thread Dennis Williamson
On Fri, Nov 13, 2015 at 10:13 AM, Griff Miller II 
wrote:

> Configuration Information [Automatically generated, do not change]:
> Machine: x86_64
> OS: cygwin
> Compiler: gcc
> Compilation CFLAGS:  -DPROGRAM='bash.exe' -DCONF_HOSTTYPE='x86_64'
> -DCONF_OSTYPE='cygwin' -DCONF_MACHTYPE='x86_64-unknown-cygwin'
> -DCONF_VENDOR='unknown' -DLOCALEDIR='/usr/share/locale' -DPACKAGE='bash'
> -DSHELL -DHAVE_CONFIG_H -DRECYCLES_PIDS   -I.
> -I/usr/src/bash-4.3.42-4.x86_64/src/bash-4.3
> -I/usr/src/bash-4.3.42-4.x86_64/src/bash-4.3/include
> -I/usr/src/bash-4.3.42-4.x86_64/src/bash-4.3/lib  -DWORDEXP_OPTION -ggdb
> -O2 -pipe -Wimplicit-function-declaration
>
> -fdebug-prefix-map=/usr/src/bash-4.3.42-4.x86_64/build=/usr/src/debug/bash-4.3.42-4
>
> -fdebug-prefix-map=/usr/src/bash-4.3.42-4.x86_64/src/bash-4.3=/usr/src/debug/bash-4.3.42-4
> uname output: CYGWIN_NT-6.1 MILLERIG1 2.3.0(0.291/5/3) 2015-11-09 10:24
> x86_64 Cygwin
> Machine Type: x86_64-unknown-cygwin
>
> Bash Version: 4.3
> Patch Level: 42
> Release Status: release
>
> Description:
> getopts doesn't always detect that a required argument is not
> supplied.
>
> Repeat-By:
> Here is a test script:
>
> #!/bin/bash
>
> # Parse command-line options.
> c=0
> opts=a:b:c
> while getopts $opts opt ; do
> case $opt in
> a)
> a=$OPTARG
> ;;
> b)
> b=$OPTARG
> ;;
> c)
> c=1
> ;;
> ?)
> exit 1
> ;;
> esac
> done
>
> echo a = \"${a}\"
> echo b = \"${b}\"
> echo c = $c
>
> % ./myscript -a a
> a = "a"
> b = ""
> c = 0
> % ./myscript -a a -b
> ./test_bash_getopts_unsilent_reporting: option requires an argument -- b
> % ./myscript -a a -b b
> a = "a"
> b = "b"
> c = 0
> % ./myscript -a -b b
> a = "-b"
> b = ""
> c = 0
>
> Note that in the last run, getopts does not detect that nothing was passed
> via -a, even though -a requires it. Instead, it thinks the next switch
> (-b) is the value of -a. Perhaps this was a conscious decision, so that
> values starting with '-' can be passed, but it's a more of a surprise to
> the developer than discovering that the user can't do e.g. ./myscript -a
> -my_a_val .  Can this bug, if it's deemed a bug, be fixed, else the
> manpage updated in the getopts section to make it clear what is going on?
>
> If there is a requirement that the user be able to have optargs that start
> with '-', maybe not allow OPTARG be one of the options in the first
> argument to getopts ($opts in the above script)?
>
> Thank you.
>
>
>
Your opts string needs to begin with a colon to enable silent error
reporting and you need to handle the colon in your case statement as the
condition where a required argument is missing.

Snippets:

opts=:a:b:c

  :) echo "Missing argument for option -$OPTARG" >&2;;

You should escape the question mark since otherwise it's a globbing
character:

  \?) echo "Unknown option: -$OPTARG" >&2; exit 1;;

-- 
Visit serverfault.com to get your system administration questions answered.


Re: Proposed Prompt Escapes

2015-11-10 Thread Dennis Williamson
On Tue, Nov 10, 2015 at 12:14 PM, Andreas Schwab <sch...@linux-m68k.org>
wrote:

> Dennis Williamson <dennistwilliam...@gmail.com> writes:
>
> > But wait, you don't need the intermediate step! It already works!!!
> >
> > prompt=$'\u, something about dominoes \U1F061  \@ '
>
> You should quote the backslashes.
>
> prompt=$'\\u, something about dominoes \U1F061  \\@ '
>
> Andreas.
>
> --
> Andreas Schwab, sch...@linux-m68k.org
> GPG Key fingerprint = 58CA 54C7 6D53 942B 1756  01D3 44D5 214B 8276 4ED5
> "And now for something completely different."
>


Thanks. That's better since it defers their evaluation which is important
when there is a conflict between the ANSI-C escapes and the prompt escapes
(e.g. \u (user) followed immediately by hex chars, \t, \v).


-- 
Visit serverfault.com to get your system administration questions answered.


Re: Proposed Prompt Escapes

2015-11-10 Thread Dennis Williamson
On Mon, Nov 9, 2015 at 5:09 PM, Dennis Williamson <
dennistwilliam...@gmail.com> wrote:

>
>
> On Thu, Nov 5, 2015 at 6:26 PM, Dennis Williamson <
> dennistwilliam...@gmail.com> wrote:
>
>> It might be handy to have some of the escapes that work in $'string'
>> quoting to also work in prompts especially now with the ${parameter@P}
>> transformation.
>>
>> Specifically the hex, unicode and control ones: \xHH, \u, \U
>> and \cx.
>>
>> I presume that the dollar-single-quote escapes should not be touched
>> since they are "specified by the ANSI C standard". Also, they needn't be
>> since we have the @P transformation.
>>
>> --
>> Visit serverfault.com to get your system administration questions
>> answered.
>>
>
>
> I obviously overlooked the collision between \u - username and \u -
> unicode. It could be dealt with by interpreting the escape as username if
> the following character is non-hex, but that would stand a good chance of
> breaking existing prompts. Since \U functionally is a complete superset of
> \u - unicode, perhaps the latter wouldn't need to be duplicated for
> prompting.
>
>
> --
> Visit serverfault.com to get your system administration questions
> answered.
>


Of course, the obvious way to do this is to assign a variable using
$'\u' or similar.

dbl_6_dom=$'\U1F061'
prompt='\u, something about dominoes $dbl_6_dom \@ '
echo "${prompt@P}"

But wait, you don't need the intermediate step! It already works!!!

prompt=$'\u, something about dominoes \U1F061  \@ '
echo "${prompt@P}"


-- 
Visit serverfault.com to get your system administration questions answered.


Re: Proposed Prompt Escapes

2015-11-09 Thread Dennis Williamson
On Thu, Nov 5, 2015 at 6:26 PM, Dennis Williamson <
dennistwilliam...@gmail.com> wrote:

> It might be handy to have some of the escapes that work in $'string'
> quoting to also work in prompts especially now with the ${parameter@P}
> transformation.
>
> Specifically the hex, unicode and control ones: \xHH, \u, \U
> and \cx.
>
> I presume that the dollar-single-quote escapes should not be touched since
> they are "specified by the ANSI C standard". Also, they needn't be since we
> have the @P transformation.
>
> --
> Visit serverfault.com to get your system administration questions
> answered.
>


I obviously overlooked the collision between \u - username and \u -
unicode. It could be dealt with by interpreting the escape as username if
the following character is non-hex, but that would stand a good chance of
breaking existing prompts. Since \U functionally is a complete superset of
\u - unicode, perhaps the latter wouldn't need to be duplicated for
prompting.


-- 
Visit serverfault.com to get your system administration questions answered.


Re: ${var@P} expansion includes 0x01 and 0x02

2015-11-09 Thread Dennis Williamson
On Fri, Nov 6, 2015 at 7:51 AM, Chet Ramey <chet.ra...@case.edu> wrote:

> On 11/5/15 7:45 PM, Dennis Williamson wrote:
>
> > That's what the \[ and \] escape sequences expand to and use to
> > communicate information to readline about invisible characters in the
> > prompt (RL_PROMPT_START_IGNORE and RL_PROMPT_END_IGNORE).  If you
> want to
> > use the expansion of ${var@P} as, for instance, the prompt passed to
> > readline when using `read -e -p prompt', those characters need to be
> there.
> >
> >
> > To follow on to what Greg said:
> >
> > The only way I've found to output a string containing non-printing
> sequence
> > delimiters using the @P transformation is to use read -e -p or to strip
> the
> > \[ and \] first. All the other prompt escapes work in printf or echo -e
> > when using @P.
>
> Let's stipulate that you're talking about interactive shells here, since
> line editing is turned off in non-interactive shells, and \[ and \] only
> expand to \001 and \002 when line editing is enabled.  (Though what I
> describe here works in non-interactive shells, too.)
>
> You can get the results you want by toggling the `emacs' option, or `vi'
> if that's what you prefer.
>
> Since \[ and \] expand to special readline characters only when readline
> (and therefore line editing) is enabled, and you don't want them expanded,
> then you should disable readline.  You can disable line editing with
> `set +o emacs +o vi' (whichever is appropriate).
>
> Run the following script to see what I mean:
>
> P='\[vis0\]\w\$\[vis1\] '
>
> echo "${P@P}" | cat -v
> set -o emacs
> echo "${P@P}" | cat -v
> set +o emacs +o vi
> echo "${P@P}" | cat -v
>
> --
> ``The lyf so short, the craft so long to lerne.'' - Chaucer
>  ``Ars longa, vita brevis'' - Hippocrates
> Chet Ramey, ITS, CWRUc...@case.edu
> http://cnswww.cns.cwru.edu/~chet/
>

With editing off, I find that I must delimit variables with braces. Without
the braces, only the second escape sequence is output. The \] isn't
terminating the variable name when editing is off.

A variation of your script:

#!/home/dennis/test/bash-4.4-beta/bash
red=$(tput setaf 1)# ^[[31m in my terminal
none=$(tput sgr0)# ^[(B^[[m in my terminal

for P in '\[vis0\]\w\$\[vis1\] ' '\[$red\]Hello\[$none\] '
'\[${red}\]Hello\[${none}\] '
do
echo "${P@P}" | cat -v
set -o emacs
echo "${P@P}" | cat -v
set +o emacs +o vi
echo "${P@P}" | cat -v

echo '= = = = = = ='
echo
done

Only the first and third values of P result in expected output for every
echo. For the second value of P, only the second echo behaves as expected.

Here is the output I get:

vis0~/test$vis1
^Avis0^B~/test$^Avis1^B
vis0~/test$vis1
= = = = = = =

^[(B^[[m
^A^[[31m^BHello^A^[(B^[[m^B
^[(B^[[m
= = = = = = =

^[[31mHello^[(B^[[m
^A^[[31m^BHello^A^[(B^[[m^B
^[[31mHello^[(B^[[m
= = = = = = =

This is for TERM=xterm. If I run it with TERM=vt100, I get similar failure.
If I set redHello=xyzzy, then "xyzzy" is output where the variable name and
the literal string are run together.

-- 
Visit serverfault.com to get your system administration questions answered.


Proposed Prompt Escapes

2015-11-05 Thread Dennis Williamson
It might be handy to have some of the escapes that work in $'string'
quoting to also work in prompts especially now with the ${parameter@P}
transformation.

Specifically the hex, unicode and control ones: \xHH, \u, \U
and \cx.

I presume that the dollar-single-quote escapes should not be touched since
they are "specified by the ANSI C standard". Also, they needn't be since we
have the @P transformation.

-- 
Visit serverfault.com to get your system administration questions answered.


Re: Paste with null delimiter

2015-11-03 Thread Dennis Williamson
On Tue, Nov 3, 2015 at 10:29 AM,  wrote:

> An example is better than thousand words:
>
> $ seq 1 2 9 > odd
> $ seq 2 2 10 > even
> $ paste -d "" odd even
> 12
> 34
> 56
> 78
> 910
> $ paste -d"" odd even
> 2
> 4
> 6
> 8
> 10
>
> Like you can see, with no space between the option (-d) and the null
> parameter (""), we have an unexpected result
>


This isn't a bash bug so this isn't the proper place for your question.

However, what is happening is that the shell evaluates the -d"", removing
the quotes and resulting in -d followed by nothing (so it's the same as if
you had typed -d by itself.

As a result, the delimiter becomes the first character of "odd" and only
one file (even) is pasted.

So

paste -d"" odd even

is the same as

paste even

Try this for comparison:

paste -d"" odd even even

-- 
Visit serverfault.com to get your system administration questions answered.


Re: Paste with null delimiter

2015-11-03 Thread Dennis Williamson
On Nov 3, 2015 12:47 PM, "Julio C. Neves" <julio.ne...@gmail.com> wrote:
>
> Thanks Dennis,
> I know that you are rigth, but "paste -d"" odd even" and "paste -d "" odd
even" are not the same? The diference is only a space between the option
and its parameter.
>
> Abcs,
> Julio
> @juliobash
>
> Próximos cursos de Shell
> Cidade Local Período
> São Paulo 4Linux 07/12 a 11/12
> Dou treinamento de Shell em qualquer cidade.
> Para mais detalhes, me mande um e-mail.
>
>
> 2015-11-03 15:47 GMT-02:00 Dennis Williamson <dennistwilliam...@gmail.com
>:
>>
>>
>>
>> On Tue, Nov 3, 2015 at 10:29 AM, <julio.ne...@gmail.com> wrote:
>>>
>>> An example is better than thousand words:
>>>
>>> $ seq 1 2 9 > odd
>>> $ seq 2 2 10 > even
>>> $ paste -d "" odd even
>>> 12
>>> 34
>>> 56
>>> 78
>>> 910
>>> $ paste -d"" odd even
>>> 2
>>> 4
>>> 6
>>> 8
>>> 10
>>>
>>> Like you can see, with no space between the option (-d) and the null
parameter (""), we have an unexpected result
>>
>>
>>
>> This isn't a bash bug so this isn't the proper place for your question.
>>
>> However, what is happening is that the shell evaluates the -d"",
removing the quotes and resulting in -d followed by nothing (so it's the
same as if you had typed -d by itself.
>>
>> As a result, the delimiter becomes the first character of "odd" and only
one file (even) is pasted.
>>
>> So
>>
>> paste -d"" odd even
>>
>> is the same as
>>
>> paste even
>>
>> Try this for comparison:
>>
>> paste -d"" odd even even
>>
>> --
>> Visit serverfault.com to get your system administration questions
answered.
>
>

No, they're different. I and others have explained how.


Bash 4.4 beta - parameter transformation - parameter attributes

2015-11-02 Thread Dennis Williamson
I considered help-bash for this, but I settled on bug-bash since it's about
an in-development version.

$ colors=(red green blue)
$ printf '%s\n' "${colors[*]@a}"
a a a

Which is consistent with the documentation:

  a  The expansion is a string consisting of flag values
representing parameter's attributes.

  If parameter is @ or *, the operation is applied to each
positional parameter in turn, and the  expansion  is  the
  resultant  list.   If  parameter  is an array variable
subscripted with @ or *, the case modification operation is
  applied to each member of the array in turn, and the
expansion is the resultant list.

But would seem to imply that each element is itself an array when they are
clearly instead elements of an array. Without the subscript, only one "a"
is output which is also consistent with the documentation.

For comparison:

$ printf '%s\n' "${colors[*]@A}"
declare -a colors=([0]="red" [1]="green" [2]="blue")
$ printf '%s\n' "${colors@A}"
declare -a colors='red'

Only  one "-a" (of course). Curiously, when there's no subscript, only a
single element is output which is consistent with long-standing Bash
behavior, but there's that "-a" which is correct. I suppose it's a case of
you get what you ask for.

$ neutral=gray
$ printf '%s\n' "${neutral[*]@A}"
neutral='gray'
$ printf '[%s]\n' "${neutral[*]@a}"
[]

In the "gray" example, the same result is given when the subscript is
omitted, of course.

I guess the point I'm trying to get to is that I don't see
how "${colors[*]@a}" or "${colors@A}" are useful whereas their opposites
are ("${colors@a}" and "${colors[*]@A}") regardless of whether the
parameter is an array or scalar. By the way, subscripting using "@" with
these transformations also doesn't seem to be useful.

It may be that this is not a matter for changing the Bash code or
documentation but that it's necessary to consider these behaviors when
making good coding practice choices.

To tell me what attributes this name has: "${var@a}"

To tell me how to reproduce this name and its contents: "${var[*]@A}"


-- 
Visit serverfault.com to get your system administration questions answered.


Re: why must bash zap last search string just because we hit ^C?

2015-10-17 Thread Dennis Williamson
On Oct 17, 2015 9:06 PM, "積丹尼 Dan Jacobson"  wrote:
>
> DW> On Fri, Oct 16, 2015 at 1:50 PM, Chet Ramey 
wrote:
>
> DW> ^C rudely aborts the entire operation.  Why assume you want to
save any
> DW> of the context?
>
> Because I got a phone call: the boss asked me to execute a shell
> command. I used ^C to get myself back to a prompt so I could type in the
> command. Now I want to resume searching and must type my
> ^Rlong_search_string all over again.
> OK I suppose I can train myself to do ^A # RET or ESC ESC # instead.

Or just open a new terminal rather than interrupting an in-progress search.


Re: why must bash zap last search string just because we hit ^C?

2015-10-16 Thread Dennis Williamson
On Fri, Oct 16, 2015 at 1:50 PM, Chet Ramey  wrote:

> On 10/16/15 3:19 AM, 積丹尼 Dan Jacobson wrote:
> > Type ^Racb^C^R^R
> > (Search backwards for abc, then hit ^C, then try searching backwards
> > some more using the last search string.)
> >
> > My problem is why must bash zap the memory of abc just because we hit ^C?
>
> ^C rudely aborts the entire operation.  Why assume you want to save any
> of the context?
>
> --
> ``The lyf so short, the craft so long to lerne.'' - Chaucer
>  ``Ars longa, vita brevis'' - Hippocrates
> Chet Ramey, ITS, CWRUc...@case.edu
> http://cnswww.cns.cwru.edu/~chet/
>
>
^G also interrupts reverse-i-search and also doesn't retain the interrupted
search string in the same way as ^C (^R^R recalls the previous search that
was terminated by enter or cursor move, etc. - (e.g. isearch-terminators) -
instead of the interrupted one).

-- 
Visit serverfault.com to get your system administration questions answered.


Re: Inconsistent arithmetic evaluation of parameters

2015-09-03 Thread Dennis Williamson
On Thu, Sep 3, 2015 at 8:45 AM, Stephane Chazelas <
stephane.chaze...@gmail.com> wrote:

> 2015-09-01 16:23:08 -0400, Greg Wooledge:
> > On Tue, Sep 01, 2015 at 03:13:57PM -0500, Dennis Williamson wrote:
> > > The version of dash I have handy (0.5.7) has math support which IMHO is
> > > broken:
> > >
> > > $ foo=bar
> > > $ bar=5
> > > $ echo $foo
> > > bar
> > > $ echo $((foo))
> > > dash: 4: Illegal number: bar
> > > $ echo $(($foo))
> > > 5
> > > $ echo $((bar))
> > > 5
> > > $ echo $(($bar))
> > > 5
> > >
> > > Note the inconsistency in support of omitting the inner dollar sign.
> >
> > $foo is expanded to bar, so the following two lines are always going to
> > be equivalent:
> >
> > echo $(($foo))
> > echo $((bar))
> >
> > POSIX also specifies (vaguely!!) that $((x)) and $(($x)) are equivalent.
>
> Note that while POSIX may (vaguely indeed) say $((x)) and
> $(($x)) are equivalent at least when x contains a litteral
> number, $((-x)) and $((-$x)) are not equivalent in all shells if
> $x contains a negative number.
>
> $ a=0 x=-1 bash -c 'echo $((a-$x))'
> bash: a--1: syntax error in expression (error token is "1")
> $ a=0 x=-1 bash -c 'echo $((a-x))'
> 1
>
> (they're OK in shells that don't implement the (optional in
> posix) -- and ++ operators like dash.
>
> Or you can add spaces to make it more reliable: $((a - $x))
>
> In ksh/zsh/bash, see also the difference between:
>
> $ a=1+1; echo $((a*2))
> 4
> $ a=1+1; echo $(($a*2))
> 3
>
> --
> Stephane
> >
> >
>
>
>
Also, for completeness:

$ a=0 x=-1 bash -c 'echo $(($a-$x))'
1



-- 
Visit serverfault.com to get your system administration questions answered.


Re: Inconsistent arithmetic evaluation of parameters

2015-09-02 Thread Dennis Williamson
On Wed, Sep 2, 2015 at 2:16 AM, Andreas Schwab <sch...@linux-m68k.org>
wrote:

> Dennis Williamson <dennistwilliam...@gmail.com> writes:
>
> > I disagree. The _expansion_ produced "bar"
>
> That's not an expansion.  Only $ introduces an expansion.
>
> Andreas.
>
>
The $ is implied.

-- 
Visit serverfault.com to get your system administration questions answered.


Re: Inconsistent arithmetic evaluation of parameters

2015-09-01 Thread Dennis Williamson
On Tue, Sep 1, 2015 at 4:24 PM, Andreas Schwab <sch...@linux-m68k.org>
wrote:

> Dennis Williamson <dennistwilliam...@gmail.com> writes:
>
> > $ echo $((foo))  # expansion succeeds, indirection fails
> > dash: 4: Illegal number: bar
>
> The indirection didn't fail, it just didn't produce a number, so the
> expression is malformed.
>
> Andreas.
>
> --
> Andreas Schwab, sch...@linux-m68k.org
> GPG Key fingerprint = 58CA 54C7 6D53 942B 1756  01D3 44D5 214B 8276 4ED5
> "And now for something completely different."
>

I disagree. The _expansion_ produced "bar" which is an "Illegal number"
because the indirection (turning "bar" into 5) didn't succeed. In Bash, the
indirection would have succeeded and the output would have been 5.

-- 
Visit serverfault.com to get your system administration questions answered.


Re: Inconsistent arithmetic evaluation of parameters

2015-09-01 Thread Dennis Williamson
On Tue, Sep 1, 2015 at 3:23 PM, Greg Wooledge <wool...@eeg.ccf.org> wrote:

> On Tue, Sep 01, 2015 at 03:13:57PM -0500, Dennis Williamson wrote:
> > The version of dash I have handy (0.5.7) has math support which IMHO is
> > broken:
> >
> > $ foo=bar
> > $ bar=5
> > $ echo $foo
> > bar
> > $ echo $((foo))
> > dash: 4: Illegal number: bar
> > $ echo $(($foo))
> > 5
> > $ echo $((bar))
> > 5
> > $ echo $(($bar))
> > 5
> >
> > Note the inconsistency in support of omitting the inner dollar sign.
>
> $foo is expanded to bar, so the following two lines are always going to
> be equivalent:
>
> echo $(($foo))
> echo $((bar))
>

It's the line above those two where I demonstrate the failure in the
indirection and equivalency.

$ echo $((foo))  # expansion succeeds, indirection fails
dash: 4: Illegal number: bar
$ echo $(($foo))  # both expansion and indirection succeed
5
$ echo $((bar))  # expansion succeeds
5
$ echo $(($bar))  # expansion succeeds
5

Bash doesn't have this inconsistency. (Just don't omit the dollar sign from
$RANDOM in most Bourne-derived shells.
https://lists.gnu.org/archive/html/bug-bash/2010-01/msg00039.html)


> POSIX also specifies (vaguely!!) that $((x)) and $(($x)) are equivalent.
>



-- 
Visit serverfault.com to get your system administration questions answered.


Re: Inconsistent arithmetic evaluation of parameters

2015-09-01 Thread Dennis Williamson
On Tue, Sep 1, 2015 at 12:50 PM, Greg Wooledge  wrote:

> On Tue, Sep 01, 2015 at 12:50:23AM -0400, Clint Hepner wrote:
> > Repeat-By:
> >
> > foo=bar
> > bar=5
> > echo $(( foo ))# produces 5
> > echo $(( foo++ ))  # produces 5
> > echo $foo  # produces 6, not bar
> > echo $bar  # produces 5, not 6
>
> bar was never changed from its value of 5, so I would say the final
> result is correct.
>
> The $(( foo++ )) part is questionable.  You've asked bash to increment
> a variable (in a math context), but that variable doesn't have an
> integer value.  But it "points to" (contains the name of) a variable
> that does.
>
> I would say that any of the following would make sense:
>
>  1) An error message is printed.
>
>  2) foo is unchanged (still contains "bar"), and bar is incremented.
>
>  3) foo takes on the value of bar, and is then incremented.
>
> Bash happens to do #3.
>
> If you think of $(( foo++ )) as being basically equivalent to
> $(( tmp=foo, foo=foo+1, tmp )) then #3 is actually quite sensible.
>
>
For comparison, ksh 93u+ and zsh 5.0.2 do the same as Bash.

The version of dash I have handy (0.5.7) has math support which IMHO is
broken:

$ foo=bar
$ bar=5
$ echo $foo
bar
$ echo $((foo))
dash: 4: Illegal number: bar
$ echo $(($foo))
5
$ echo $((bar))
5
$ echo $(($bar))
5

Note the inconsistency in support of omitting the inner dollar sign. Also
post increment produces an error and pre increment produces no error and no
action:

$ echo $(($foo++))
dash: 9: arithmetic expression: expecting primary: "bar++"
$ echo $(($bar++))
dash: 10: arithmetic expression: expecting primary: "5++"
$ echo $((++$foo))
5
$ echo $foo
bar
$ echo $bar
5
$ echo $((++$bar))
5
$ echo $bar
5



-- 
Visit serverfault.com to get your system administration questions answered.


Re: bash displays strange characters after base64 decoding

2015-08-06 Thread Dennis Williamson
On Thu, Aug 6, 2015 at 12:45 PM, Valentin Schmidt v...@posteo.org wrote:

 From: v...@posteo.org
 To: bug-bash@gnu.org,b...@packages.debian.org
 Subject: bash displays strange characters after base64 decoding

 Configuration Information:
 Machine: x86_64
 OS: linux-gnu
 Compiler: gcc
 Compilation CFLAGS:  -DPROGRAM='bash' -DCONF_HOSTTYPE='x86_64'
 -DCONF_OSTYPE='linux-gnu' -DCONF_MACHTYPE='x86_64-pc-linux-gnu'
 -DCONF_VENDOR='pc' -DLOCALEDIR='/usr/share/locale' -DPACKAGE='bash' -DSHELL
 -DHAVE_CONFIG_H   -I.  -I../. -I.././include -I.././lib -D_FORTIFY_SOURCE=2
 -g -O2 -fstack-protector --param=ssp-buffer-size=4 -Wformat
 -Werror=format-security -Wall
 uname output: Linux ongakui 3.13.0-24-generic #47-Ubuntu SMP Fri May 2
 23:30:00 UTC 2014 x86_64 x86_64 x86_64 GNU/Linux
 Machine Type: x86_64-pc-linux-gnu

 Bash Version: 4.3
 Patch Level: 11
 Release Status: release

 Description:
 Bash displays strange characters (including command prompt) (see attached
 png file) after the execution of the base64 (GNU coreutils 8.21) command
 like described as follows:
 base64 -d base64.txt
 The aim was actually to direct the output of the base64 command into a
 file (would have been a .jpg file) but the decoded.jpg was forgotten.
 Accordingly the output was directed to stdout instead. This resulted in
 the command prompt consisting of strange characters after decoding.
 Also any command entered via the keyboard resulted in strange characters
 being displayed instead of the typed characters.
 Also the output of the ls (which seems to be executed) command (as an
 example) is displayed as strange characters.

 Repeat-By:
 As described above.


Not a bug. Also not Bash related. You have sent control characters to your
terminal which causes it to display alternate characters.

Try entering the reset command (you'll have to do it more or less blindly).

-- 
Visit serverfault.com to get your system administration questions answered.


Re: $() does not handle nesting with case - parser precedence?

2015-06-28 Thread Dennis Williamson
On Sat, Jun 27, 2015 at 2:48 PM, Nathan Neulinger nn...@neulinger.org
wrote:

 Configuration Information [Automatically generated, do not change]:
 Machine: x86_64
 OS: linux-gnu
 Compiler: gcc
 Compilation CFLAGS:  -DPROGRAM='bash' -DCONF_HOSTTYPE='x86_64'
 -DCONF_OSTYPE='linux-gnu' -DCONF_MACHTYPE='x86_64-redhat-linux-gnu'
 -DCONF_VENDOR='redhat' -DLOCALEDIR='/usr/share/locale' -DPACKAGE='bash'
 -DSHELL -DHAVE_CONFIG_H   -I.  -I. -I./include -I./lib  -D_GNU_SOURCE
 -DRECYCLES_PIDS -DDEFAULT_PATH_VALUE='/usr/local/bin:/usr/bin'  -O2 -g
 -pipe -Wall -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2 -fexceptions
 -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches
 -m64 -mtune=generic
 uname output: Linux skyhawk.home.neulinger.org 3.19.3-200.fc21.x86_64 #1
 SMP Thu Mar 26 21:39:42 UTC 2015 x86_64 x86_64 x86_64 GNU/Linux
 Machine Type: x86_64-redhat-linux-gnu

 Bash Version: 4.3
 Patch Level: 39
 Release Status: release

 Description:

 If $() includes a case statement nested within it, the parser is
 not matching ) as closing the case,
 but rather the $(. This behavior is different between bash and
 other shells. ksh/busybox
 both process this without error, but I do not know which is
 officially correct.

 Test Case:
 ---
 testing=$(
 echo test | while read line; do
 case $line in
  test)  echo saw test ;;
  *) echo other ;;
 esac
 done
 )

 echo result: $testing
 --

 Expected output:

 result: saw test

 Actual output:

 parse-bug.sh: line 6: syntax error near unexpected token `;;'
 parse-bug.sh: line 6: ` test)  echo saw test ;;'


 Workaround:  Use (test) instead of test) in the nested code


 Repeat-By:
 Run script with that syntax.



 --
 
 Nathan Neulinger   nn...@neulinger.org
 Neulinger Consulting   (573) 612-1412



You can use the full syntax of case by surrounding the cases with both
opening and closing parentheses:

testing=$(
echo test | while read line; do
case $line in
 (test)  echo saw test ;;
 (*) echo other ;;
esac
done
)

POSIX shows the opening parentheses as optional, but does not describe
their use or when they might be necessary.

http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_09_04

-- 
Visit serverfault.com to get your system administration questions answered.


Re: Bug, feature or just the correct behaviour (stat'ing -bash down the PATH)

2015-06-03 Thread Dennis Williamson
On Tue, Jun 2, 2015 at 5:47 PM, Dave Rutherford d...@evilpettingzoo.com
wrote:


 It is ironic yet somehow appropriate that a fusion energy center
 should be having such a 1997 sort of problem today.  But
 truly, my sympathies. :-)

 Dave


How about a nuclear plant having a '70s kind of problem?

https://ca.linkedin.com/jobs2/view/28135735

-- 
Visit serverfault.com to get your system administration questions answered.


Re: Problem with brace expansion

2015-04-21 Thread Dennis Williamson
On Tue, Apr 21, 2015 at 2:44 PM, Dr Alun J. Carr alun.j.c...@runbox.com
wrote:

 There appears to be a bug in bash when using a variable in curly brace
 expansion, e.g., {1..$n}. I have put the two following test scripts in the
 attached files looper1.sh and looper2.sh:

 #looper1.sh
 for i in {1..4}
 do
 echo i = $i
 done

 #looper2.sh
 n=4
 for i in {1..$n}
 do
 echo i = $i
 done

 Tests were done with bash, ksh, zsh, pdksh, dash and heirloom System V
 Bourne sh with the following versions:
 bash3.2.57(1)
 bash4.3.33(1)
 ksh version sh (ATT Research) 93u+ 2012-08-01
 zsh 5.0.5 (x86_64-apple-darwin14.0)
 pdksh   stable 5.2.14
 dashstable 0.5.8
 sh  ???

 Results for bash (both versions give the same result); note that bash
 fails to expand the curly brace expression in only the second case:

 $ bash looper1.sh
 i = 1
 i = 2
 i = 3
 i = 4

 $ bash looper2.sh
 i = {1..4}

 Repeating using ksh we get correct expansion of the curly braces:

 $ ksh looper1.sh
 i = 1
 i = 2
 i = 3
 i = 4

 $ ksh looper2.sh
 i = 1
 i = 2
 i = 3
 i = 4

 And using zsh, the same result as for ksh:

 $ zsh looper1.sh
 i = 1
 i = 2
 i = 3
 i = 4

 $ zsh looper2.sh
 i = 1
 i = 2
 i = 3
 i = 4

 Neither pdksh (which installs as ksh using homebrew) nor dash handle
 either case correctly:

 pdksh:

 $ /usr/local/bin/ksh looper1.sh
 i = {1..4}

 $ /usr/local/bin/ksh looper2.sh
 i = {1..4}

 dash:

 $ dash looper1.sh
 i = {1..4}

 $ dash looper2.sh
 i = {1..4}

 The System V sh from the heirloom project behaves the same way as pdksh
 and dash (or more correctly, since System V is really the reference, pdksh
 and dash behave the same way as SysV sh):

 $ 5 sh looper1.sh
 i = {1..4}

 $ 5 sh looper2.sh
 i = {1..4}




Bash performs brace expansion before variable expansion and thus does not
support the feature that zsh and ksh have which do variable expansion
before brace expansion.

To use a variable, use C-style for loops:

for ((i = 1; i = 4; i++))

-- 
Visit serverfault.com to get your system administration questions answered.


Re: Incorrect manage * in test -z

2015-04-17 Thread Dennis Williamson
On Thu, Apr 16, 2015 at 6:51 PM, Guillermo Buritica Tobon 
gburitic...@gmail.com wrote:

 Hi All.

 H have the next bash script code.:

 #!/bin/sh
 # Pring OK on empty input,
 # Print input on non-empty input

 read INPUT
 if [ -z $INPUT ]; then
 echo OK
 else
 echo $INPUT
 while read INPUT; do
 echo $INPUT
 done
 fi


 The function read one input and print the input or print OK if the input
 is enpty

 Example correct use:

 echo Hello World | ~/OkIfNoInput.sh
 Hello World

 echo  | ~/OkIfNoInput.sh
 OK

 The ISSUE is when the string Contain * the results are very estrange. or
 *[space]

 echo * Hello World * |  ~/OkIfNoInput.sh
 forensic orbit-gtobon postgresql-2015-04-13_00.log qt_temp.kn3231
 qt_temp.Lh3231 qt_temp.nS3231 qt_temp.T28137 query.html server.log
 smartgrep_60863524962e4077d558766bf2f79235a373cae448da3e11b384b37e7d2f1ea8
 ssh-Mxs2Qb6AhJxc systemd-private-1AfwYz systemd-private-2stQfP
 systemd-private-2ytw5H systemd-private-3xYsUI systemd-private-44tvlt
 systemd-private-4FOgxG systemd-private-cfGpBQ systemd-private-d6PHV1
 systemd-private-EQaIzh systemd-private-FZx2ad systemd-private-GJzO5O
 systemd-private-GTYlPD systemd-private-H72F9i systemd-private-I6N6mv
 systemd-private-isBta7 systemd-private-m70a9b systemd-private-missS7
 systemd-private-mPbVbC systemd-private-noY0rf systemd-private-nZbmwS
 systemd-private-obDFE9 systemd-private-OfXH6S systemd-private-P6I7QK
 systemd-private-PI2Kf0 systemd-private-Q8dNwo systemd-private-qiMHMr
 systemd-private-QiOvUZ systemd-private-RO0WgV systemd-private-t2Slaz
 systemd-private-UH50C8 systemd-private-yJIqqS tt.txt
 zabbix_server_5662.pinger zabbix_server_5680.pinger Hello World forensic
 orbit-gtobon postgresql-2015-04-13_00.log qt_temp.kn3231 qt_temp.Lh3231
 qt_temp.nS3231 qt_temp.T28137 query.html server.log
 smartgrep_60863524962e4077d558766bf2f79235a373cae448da3e11b384b37e7d2f1ea8
 ssh-Mxs2Qb6AhJxc systemd-private-1AfwYz systemd-private-2stQfP
 systemd-private-2ytw5H systemd-private-3xYsUI systemd-private-44tvlt
 systemd-private-4FOgxG systemd-private-cfGpBQ systemd-private-d6PHV1
 systemd-private-EQaIzh systemd-private-FZx2ad systemd-private-GJzO5O
 systemd-private-GTYlPD systemd-private-H72F9i systemd-private-I6N6mv
 systemd-private-isBta7 systemd-private-m70a9b systemd-private-missS7
 systemd-private-mPbVbC systemd-private-noY0rf systemd-private-nZbmwS
 systemd-private-obDFE9 systemd-private-OfXH6S systemd-private-P6I7QK
 systemd-private-PI2Kf0 systemd-private-Q8dNwo systemd-private-qiMHMr
 systemd-private-QiOvUZ systemd-private-RO0WgV systemd-private-t2Slaz
 systemd-private-UH50C8 systemd-private-yJIqqS tt.txt
 zabbix_server_5662.pinger zabbix_server_5680.pinger


 echo * |  ~/OkIfNoInput.sh
 forensic orbit-gtobon postgresql-2015-04-13_00.log qt_temp.kn3231
 qt_temp.Lh3231 qt_temp.nS3231 qt_temp.T28137 query.html server.log
 smartgrep_60863524962e4077d558766bf2f79235a373cae448da3e11b384b37e7d2f1ea8
 ssh-Mxs2Qb6AhJxc systemd-private-1AfwYz systemd-private-2stQfP
 systemd-private-2ytw5H systemd-private-3xYsUI systemd-private-44tvlt
 systemd-private-4FOgxG systemd-private-cfGpBQ systemd-private-d6PHV1
 systemd-private-EQaIzh systemd-private-FZx2ad systemd-private-GJzO5O
 systemd-private-GTYlPD systemd-private-H72F9i systemd-private-I6N6mv
 systemd-private-isBta7 systemd-private-m70a9b systemd-private-missS7
 systemd-private-mPbVbC systemd-private-noY0rf systemd-private-nZbmwS
 systemd-private-obDFE9 systemd-private-OfXH6S systemd-private-P6I7QK
 systemd-private-PI2Kf0 systemd-private-Q8dNwo systemd-private-qiMHMr
 systemd-private-QiOvUZ systemd-private-RO0WgV systemd-private-t2Slaz
 systemd-private-UH50C8 systemd-private-yJIqqS tt.txt
 zabbix_server_5662.pinger zabbix_server_5679.pinger



 This is an expected result?
 I'm doing something wrong?
 Or is this a bug in bash?



 Kind Regards


 Guillermo Buritica T.


Always quote your variables. The problem comes from

echo $INPUT

which should be

echo $INPUT

-- 
Visit serverfault.com to get your system administration questions answered.


Re: Incorrect manage * in test -z

2015-04-17 Thread Dennis Williamson
On Fri, Apr 17, 2015 at 8:55 AM, Eduardo A. Bustamante López 
dual...@gmail.com wrote:

  Always quote your variables. The problem comes from
 
  echo $INPUT
 
  which should be
 
  echo $INPUT

 Someone derped. It *should* be

  echo $INPUT

 --
 Eduardo Bustamante
 https://dualbus.me/



Yes, I derped.

-- 
Visit serverfault.com to get your system administration questions answered.


Re: Documentation Update

2014-12-12 Thread Dennis Williamson
On Fri, Dec 12, 2014 at 12:32 PM, Bob Proulx b...@proulx.com wrote:

 Greg Wooledge wrote:
  David J. Haines wrote:
   When started interactively, bash sets the extglob shopt; however, that
   fact seems to have been overlooked in the manpage.
 
  This is a compile-time setting.  Your vendor probably turned this on.
 
  imadev:~$ bash-4.3
  imadev:~$ shopt | grep extglob
  extglob off
  imadev:~$ exit

 Also some vendors place a lot of customization in /etc/profile,
 /etc/profile.d/*, /etc/bash_otherplaces sourced in the above.  It
 might be turned on by one of those.

 I see a lot of hits in the bash_completion add-on files.  Should we be
 looking at:

   $ grep -r shopt -s extglob /etc/bash*
   /etc/bash_completion.d/nmh:shopt -s extglob
   /etc/bash_completion.d/libreoffice.sh:test $g -eq 0  shopt -s
 extglob
   /etc/bash_completion.d/mercurial:shopt -s extglob
   /etc/bash_completion.d/subversion:# pattern matching enabled (use 'shopt
 -s extglob progcomp' to enable
   /etc/bash_completion.d/subversion:shopt -s extglob

 Bob


Perhaps you should check for shopt -u extglob reversing those.

-- 
Visit serverfault.com to get your system administration questions answered.


Re: [PATCH] bracketed paste support

2014-10-31 Thread Dennis Williamson
On Thu, Oct 30, 2014 at 1:45 PM, Daniel Colascione dan...@dancol.org
wrote:


 Sure, you might argue that users should paste into a trusted
 intermediate location --- say a text editor --- inspect the code, and
 then paste into the shell. That would be the prudent thing to do, but
 users don't actually *do* that and never will.



And you have communities whose idea of an installer is wget | bash. I'm
looking at you [redacted].


Re: Not so useless use of cat

2014-09-16 Thread Dennis Williamson
On Tue, Sep 16, 2014 at 2:03 AM, Ralf Goertz me@myprovider.invalid wrote:

 Am Sat, 13 Sep 2014 12:53:48 -0600
 schrieb Bob Proulx b...@proulx.com:


  Dennis Williamson wrote:
   Bob Proulx wrote:
  { for i in file[12] ; do cat $i ; done ;}  both

   There's no need for the curly braces and the last semicolon.
 
  Of course you are totally right.  I was distracted by the subshell as
  a concept.  For re-stitching file with redirections a subshell isn't
  needed and a list is convenient.
 
   Note that the loop in this case can be replaced by
  
   cat file[12]  both
  
   I failed to spot that in my earlier reply.
 
  Me too.  (But usually these are from more complex examples that can't
  be simplified as much.  It is just that all of the details aren't
  shown.)

 Actually things are more complicated. I do need the /dev/stdout part. I
 obiously don't have the problem with `cat' but with some other program
 that doesn't write to stdout per se and expects a -o parameter for the
 output file. And this program just accepts one input file. I merely used
 the first `cat' in my example to make my point. So what I wanted was

 $ for i in file[12] ; do program -i $i -o /dev/stdout ; done  outfile

 which I assumed to be elegant and would do as I expected except it
 didn't and I really thought it could have been a bug. That's why I
 reported it here.

 Thanks for all replys,

 Ralf



Does your program support using a hyphen to represent stdout (some do)?

program -i $i -o -

-- 
Visit serverfault.com to get your system administration questions answered.


Re: Not so useless use of cat

2014-09-12 Thread Dennis Williamson
On Sep 12, 2014 6:42 PM, Ralf Goertz me@myprovider.invalid wrote:

 Hi,

 Why do I need cat (the second on) here?

 $ echo first file1
 $ echo second file2
 $ (for i in file[12] ; do cat $i  /dev/stdout ; done) | cat  both

 $ cat both
 first
 second

 

 If I omit the | cat after the loop I get

 $ cat both
 second

 Even when using  both instead of  both only second makes it
 into both. Why? I would have thought that using a subshell should be
 enough to protect the both from being overwritten.

 Ralf



Also remove the redirection to stdout and the subshell

for ... done  both


  1   2   >