1 linux variables bash shell scripting
我想定义一个变量,它将在每次使用时进行评估.
我的目标是定义两个变量:
A=/home/userA
B=$A/my_file
Run Code Online (Sandbox Code Playgroud)
因此,每当我更新时A,B都会更新新值,A
我知道如何在提示变量中执行此操作,但是,有没有办法为常规变量执行此操作?
如果你有Bash 4.4或更新版本,你可以(ab)使用参数扩展,它扩展就好像它是一个提示字符串:${parameter@P} parameter
$ A='/home/userA'
$ B='$A/my_file' # Single quotes to suppress expansion
$ echo "${B@P}"
/home/userA/my_file
$ A='/other/path'
$ echo "${B@P}"
/other/path/my_file
Run Code Online (Sandbox Code Playgroud)
但是,正如评论中指出的那样,使用函数更简单,更便携:
$ appendfile() { printf '%s/%s\n' "$1" 'my_file'; }
$ A='/home/user'
$ B=$(appendfile "$A")
$ echo "$B"
/home/user/my_file
$ A='/other/path'
$ B=$(appendfile "$A")
$ echo "$B"
/other/path/my_file
Run Code Online (Sandbox Code Playgroud)