1
  animal_name=""

  if [[ -z "${!animal_name// }" ]]; then
   animal_name="doggo"
  fi
    
 echo sudo chmod ...... ${!animal_name}

Is there any way to reference a variable in bash?

lost9123193
  • 10,460
  • 26
  • 73
  • 113

4 Answers4

3

Ditch the "{}"

animal_name=""
if [[ -z "$animal_name" ]]; then
    animal_name="doggo"
fi

sudo chmod {flag} $animal_name
kiwibg
  • 334
  • 2
  • 9
0

I think your error is in line 3 (or 2, depending on how you look at it.)

animal_name=""

if [[ -z "${!animal_name// }" ]]; then # Error: event not found: animal_name//
animal_name="doggo"
fi

echo sudo chmod ...... $animal_name

The fix that I found was to remove the 2 slashes in "${!animal_name// }" and that worked for me.

Base64__
  • 97
  • 8
  • Edited to include the `chmod ......`. Could you provide some more background? like do you have a file/executable named doggo? what's the purpose of `sudo chmod ...... {!animal_name}`? – Base64__ Aug 25 '20 at 21:50
  • oh i think im getting this mixed up with javascript... do you know what {!animal_name} means when I include {! }? – lost9123193 Aug 25 '20 at 21:59
0

If you are just trying to make sure the variable has some value, you can use defaults.

echo sudo chmod ...... ${animal_name:-doggo}

This will use doggo is animal_name is empty, but will leave it empty.

$: animal_name=
$: echo sudo chmod ...... ${animal_name:-doggo}
sudo chmod ...... doggo
$: echo "[$animal_name]" # still empty
[]
$: animal_name=bob
$: echo sudo chmod ...... ${animal_name:-doggo} # doesn't change is already set
sudo chmod ...... bob

If you want animal_name to ALWAYS default to doggo thereafter, use = instead of - and it will assign it as well if it's empty.

echo sudo chmod ...... ${animal_name:=doggo}

so:

$: animal_name=
$: echo sudo chmod ...... ${animal_name:=doggo}
sudo chmod ...... doggo
$: echo "[$animal_name]" # this time it was set
[doggo]
$: animal_name=bob
$: echo sudo chmod ...... ${animal_name:=doggo} # doesn't change if already set
sudo chmod ...... bob
Paul Hodges
  • 13,382
  • 1
  • 17
  • 36
0

Probably you mean indirection? This may help.

animal_name=""
doggo="I am doggo!"
if [[ -z "${animal_name}" ]]; then
  animal_name="doggo"
fi

echo sudo chmod ...... ${!animal_name}

The ${!animal_name} reference the value of doggo, so the output is:

sudo chmod ...... I am doggo!
LingSamuel
  • 496
  • 5
  • 10