[英]Execute a random script in a folder
I need to run a random script in a folder.我需要在一个文件夹中运行一个随机脚本。 I can use 'ls -1 /home/sepinto/EML-Samples/scripts/regular |
我可以使用 'ls -1 /home/sepinto/EML-Samples/scripts/regular | sort -R |
排序-R | head -1' to get a random file name but how can I execute it?
head -1' 获取随机文件名,但我该如何执行它?
Thanks谢谢
I can use 'ls -1 /home/sepinto/EML-Samples/scripts/regular |我可以使用 'ls -1 /home/sepinto/EML-Samples/scripts/regular | sort -R |
排序-R | head -1' to get a random file name but how can I execute it?
head -1' 获取随机文件名,但我该如何执行它?
It depends on the shell you are using.这取决于您使用的 shell。 I will assume your shell is bash or sh and the scripts are already executable.
我假设您的 shell 是 bash 或 sh 并且脚本已经可执行。
Then all you need to do is enclose your command line above in backticks .然后你需要做的就是用反引号将上面的命令行括起来。 Everything you type between backticks is evaluated (executed) by the shell and then replaced by the command's output.
您在反引号之间键入的所有内容都由 shell 评估(执行),然后由命令的 output 替换。
`ls -1 /home/sepinto/EML-Samples/scripts/regular | sort -R | head -1`
Edit:编辑:
Turns out that the path is stripped if ls -1 is piped into another command.事实证明,如果 ls -1 通过管道传输到另一个命令中,路径将被删除。
A solution is to store the path in a variable so you can use it twice:一种解决方案是将路径存储在变量中,以便您可以使用它两次:
d="/home/sepinto/EML-Samples/scripts/regular"; $d/`ls -1 $d/ | sort -R | head -1`
First, change your ls command to list the files with complete path, then just execute them either directly with backticks or storing them in a variable.首先,更改 ls 命令以列出具有完整路径的文件,然后直接使用反引号执行它们或将它们存储在变量中。
SCRIPTNAME=`ls -1 /home/sepinto/EML-Samples/scripts/regular/*.sh | sort -R | head -1`
echo "Executing $SCRIPTNAME"
"$SCRIPTNAME"
The above assumes that all your files have a.sh ending, change the ls
argument if this is not the case.上面假设所有文件都以 a.sh 结尾,如果不是这种情况,请更改
ls
参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.