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.
CodePudding user response:
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).