0

I'm creating shell script in Ubuntu 20.04 VM, so I'm testing in bash the following:

echo ${"/mnt/raid1/"//\//}

What I need to achieve is to get the folder's route as valid variable name, something like 'mntraid1'. However previous code throws bash error - bad substitution.

Any orientation appreciated.

5
  • bash, or sh? They're not the same. Commented Apr 24, 2022 at 19:08
  • In particular, sh isn't guaranteed to support ${var//find/subst} at all. Commented Apr 24, 2022 at 19:08
  • My actual goal is to create a shell script but since it wasn't working I'm testing it on bash, I'm sorry if they are different questions, I actually don't know. Commented Apr 24, 2022 at 19:11
  • If you do want to use this feature, be sure you're writing a bash script instead of a sh script. They're both "shell scripts", but bash guarantees a larger set of features. Commented Apr 24, 2022 at 19:11
  • (Moreover, if you're dynamically generating variable names, it's much easier to work with them using other bash extensions -- with baseline POSIX sh you're stuck with eval, and there's a lot of security impact when it's used carelessly; whereas bash gives you indirect references so you can use "variable variables" safely). Commented Apr 24, 2022 at 19:13

1 Answer 1

1

Only a variable name can be in the first position of this parameter expansion. Thus, you must assign your string to a variable before running a substitution on it.

#!/usr/bin/env bash
#              ^^^^- this makes your script a bash script

# for extra paranoia, one can add an explicit version check
# otherwise, a user running 'sh yourscript' can override the shebang above
case $BASH_VERSION in '') echo "This script requires bash" >&2; exit 1;; esac

dev=/mnt/raid1
var=${dev//'/'/}
echo "Variable name corresponding to $dev is $var"

Note that this is an extension not guaranteed by the POSIX sh standard. It is thus unsafe to use in any script with a #!/bin/sh shebang (which only guarantees functionality required by that standard).

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your answer, I think my problem has to do with not being able make my script a bash one, because the code provided by you is working in a VM with another OS. When I add !/usr/bin/env bash, it throws not found error.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.