Home > Blockchain >  Execute a random script in a folder
Execute a random script in a folder

Time:01-27

I need to run a random script in a folder. I can use 'ls -1 /home/sepinto/EML-Samples/scripts/regular | sort -R | head -1' to get a random file name but how can I execute it?

Thanks

I can use 'ls -1 /home/sepinto/EML-Samples/scripts/regular | sort -R | head -1' to get a random file name but how can I execute it?

CodePudding user response:

It depends on the shell you are using. I will assume your shell is bash or sh and the scripts are already executable.

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.

`ls -1 /home/sepinto/EML-Samples/scripts/regular | sort -R | head -1`

CodePudding user response:

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.

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.

  • Related