我有一个非常简单的脚本,如下所示:
#!/bin/bash
VAR1="$1"
MOREF='sudo run command against $VAR1 | grep name | cut -c7-'
echo $MOREF
Run Code Online (Sandbox Code Playgroud)
当我从命令行运行此脚本并将参数传递给它时,我没有得到任何输出.但是,当我运行$MOREF变量中包含的命令时,我能够获得输出.
我想知道如何获取需要在脚本中运行的命令的结果,将其保存到变量,然后在屏幕上输出该变量?
我一直在尝试从程序输出中读取环境变量的输入,如下所示:
echo first second | read A B ; echo $A-$B
Run Code Online (Sandbox Code Playgroud)
结果是:
-
Run Code Online (Sandbox Code Playgroud)
A和B都是空的.我读到了bash在子shell中执行管道命令,并且基本上阻止了管道输入读取.但是,以下内容:
echo first second | while read A B ; do echo $A-$B ; done
Run Code Online (Sandbox Code Playgroud)
似乎工作,结果是:
first-second
Run Code Online (Sandbox Code Playgroud)
有人可以解释一下这里的逻辑是什么吗?是while...... done构造中的命令实际上是在同一个shell中执行echo而不是在子shell中执行?
我目前正在编写一个bash脚本,使用GoogleCL将视频文件加载到YouTube .
正如我在循环中上传内容(因为可能有多个视频文件)我想检查每个文件是否已成功上传,然后再上传下一个文件.
该命令google youtube post --access unlisted --category Tech $f(其中$ f表示文件)输出一个字符串,告诉我上传是否成功.
但我不知道如何将"返回字符串"重定向到变量中以检查成功.
这就是我的意思:
for f in ./*.ogv ./*.mov ./*.mp4
do
if [[ '*' != ${f:2:1} ]]
then
echo "Uploading video file $f"
# How to put the return value of the following command into a variable?
google youtube post --access unlisted --category Tech $f > /dev/null
# Now I assume that the output of the command above is available in the variable RETURNVALUE
if [[ …Run Code Online (Sandbox Code Playgroud) 我有一些shell命令.我想将输出写入标准输出并将其保存到变量中.我想用一个命令来解决它.我试过这些东西.
ls > $VAR # redirects the output to file which name is stored in $VAR
ls | tee -a $VAR # writes to standard output as well as in file which name is stored in $VAR
VAR=`ls` # output into $VAR, but it is not sent to standard output
VAR=`ls`;echo $VAR # ok, it works but these are two commands
Run Code Online (Sandbox Code Playgroud)
任何的想法?
bash ×3
shell ×2
command-line ×1
ksh ×1
pipe ×1
piping ×1
return-value ×1
scripting ×1
while-loop ×1