2

I want to attach a string to each of the elements in an array in bash, but not if the array is empty.

Currently this works for non-empty arrays:

$ cat this.sh
#!/bin/bash
lst=$@
lst[0]="a"
lst[1]="b"
echo ${lst[@]/%/.ext}
$ bash this.sh
a.ext b.ext

But it fails for an empty array:

$cat that.sh 
#!/bin/bash
lst=$@
echo ${lst[@]/%/.ext}
$ bash that.sh 
.ext

So this fails, as I want the string to be empty, if the array is empty.

Restriction: I can't use an if-statement or loop constructs in this particular situation.

3
  • Can you use tests without if? eg [ ${#lst} -gt 0 ] && echo ${lst[@]/%/.ext} Incidentally, your lst variable isn't initially an array, just a string containing all the positional parameters. Commented May 8, 2014 at 15:07
  • @JoshJolly: no, unfortunately I can't use this. Commented May 8, 2014 at 15:11
  • How is your program supposed to do something under a certain condition if you dont test for the condition ? Are you allowed to use awk or sed ? Commented May 8, 2014 at 15:15

2 Answers 2

2

There's a slight misunderstanding in your OP. In your second example, lst is not an empty array. Check this out: add the line declare -p lst at the end of your script (the declare builtin used with the -p option will print out the information about the given variable):

#!/bin/bash
lst=$@
declare -p lst

then run your script:

$ ./myscript
declare -- lst=""

So for Bash, your lst is just an empty string (yet it is set). Look what an empty array is:

$ a=()
$ declare -p a
declare -a a='()'

and look what happens if I run your echo command:

$ echo ${a[@]/%/.ext}

$

did you see that? it's really empty!

I want to say that it really hurt me when I wrote echo ${a[@]/%/.ext} without quotes! the proper way would be:

$ echo "${a[@]/%/.ext}"

$

(still empty, eh).

Now you probably mean:

#!/bin/bash
lst=( "$@" )
echo "${lst[@]/%/.ext}"

I called this script banana, I chmod +x banana and I played with it:

$ ./banana

$ ./banana one two
one.ext two.ext
$ ./banana "one one" two
one one.ext two.ext
$ ./banana one ""
one.ext .ext
Sign up to request clarification or add additional context in comments.

Comments

2

In your second case, lst isn't an empty array: it's just an empty string. Ensure that lst is an array by using

ls=( "$@" )

In your first case, lst is an array because you ignore the initial assignment to lst by overwriting it with the following indexed assignments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.