命令前的Bash变量分配 [英] Bash variable assignment before command
问题描述
几天前,我遇到了一个命令
A couple of days ago I came across a command
AWS_ACCESS_KEY="foo" AWS_SECRET_KEY="bar" aws list iam
我看到在命令之前设置变量会在命令的环境中添加这些变量:
I see that setting variables before a command adds those variables in the command's environment:
#make sure there is no environment variable "foo"
$ echo $foo
#mimic-ing above command
$ foo=bar printenv | grep foo
foo=bar
#or trying from python environment
$foo=bar python -c "import os; print(os.getenv('foo', None))"
bar
#foo is destroyed now
$ echo $foo
#<<NOTHING
我正尝试使用此技巧根据今天的日期动态创建一个新目录:
I was trying to use this trick to dynamically create a new directory based on today's date:
$ dname=$(date +%d_%m_%y) mkdir ${dname} && cd ${dname}
但出现以下错误:
mkdir: missing operand
Try 'mkdir --help' for more information.
即dname=$(date +%d_%m_%y) echo $dname
返回空!
我做错了什么?如何在bash的同一行上动态创建和使用are变量?
What am I doing wrong? How can I dynamically create and use are variable on the same line in bash?
推荐答案
在$()
内部运行命令之前,Shell会替换您的变量.您可以使用&&
使其适合您:
Shell is substituting your variable before running the command inside $()
. You can use &&
to make it work for you:
dname=$(date +%d_%m_%y) && mkdir ${dname} && cd ${dname}
或者,当然:
dname=$(date +%d_%m_%y); mkdir ${dname} && cd ${dname}
但是,如果要在其中捕获环境变量,dname
将对mkdir
可用.
However, dname
would be available to mkdir
if it were to grab the environment variable inside.
比方说,我们有一个脚本test.sh
,其中包含一个单独的语句echo $dname
.然后:
Let's say we have a script test.sh
that has a single statement echo $dname
inside. Then:
dname=$(date +%d_%m_%y) ./test.sh
将产生产量:
07_03_17
这与您的aws
命令行的工作方式一致.
This is consistent with how your aws
command line worked.
类似的帖子: