In some situations when executing a command or a Linux shell script we may require some manual intervention. The yes command is simple built-in command which will help you remove this manual intervention stuff in your scripts. The yes command is a cousin of echo command both print what we given. Only difference is echo will print only once, but yes will print until we intervene. Below are some examples which will come handy when simulating yes/no in scripts/commands
Example 1: Simulate yes when using rm command. My rm command is aliased to “rm -rf”, so for this example I am using rm -i for this example. Remove all files in my directory.
surendra@linuxnix:~/code/sh/temp$ touch {1..5} surendra@linuxnix:~/code/sh/temp$ yes | rm -i * rm: remove regular empty file ‘1’? rm: remove regular empty file ‘2’? rm: remove regular empty file ‘3’? rm: remove regular empty file ‘4’? rm: remove regularempty file ‘5’? surendra@linuxnix:~/code/sh/temp$ ls surendra@linuxnix:~/code/sh/temp$
Example 2: Do not remove any files with rm
surendra@linuxnix:~/code/sh/temp$ touch {1..5} surendra@linuxnix:~/code/sh/temp$ yes n | rm -i * rm: remove regular empty file ‘1’? rm: remove regular empty file ‘2’? rm: remove regular empty file ‘3’? rm: remove regular empty file ‘4’? rm: remove regular empty file ‘5’? surendra@linuxnix:~/code/sh/temp$ ls 1 2 3 4 5
Example 3: Simulate yes and no in a controled fashon. I want to remove 1, 3, 5 files from my directory.
surendra@linuxnix:~/code/sh/temp$ ls 1 2 3 4 5 surendra@linuxnix:~/code/sh/temp$ echo -e "y\nn\ny\nn\ny" | rm -i * rm: remove regular empty file ‘1’? rm: remove regular empty file ‘2’? rm: remove regular empty file ‘3’? rm: remove regular empty file ‘4’? rm: remove regular empty file ‘5’? surendra@linuxnix:~/code/sh/temp$ ls 2 4
Example 4: How about taking input from user for yes, no stuff? We can use bash regular expressions for that.
if [[ “$var1″ =~ ([Yy]|([Ee][Ss])) ]]
then
echo “Yes, it’s present”
else
echo “it’s not present”
fi
Did not understand regular expressions, then see below links.
Latest posts by Surendra Anne (see all)
- Docker: How to copy files to/from docker container - June 30, 2020
- Anisble: ERROR! unexpected parameter type in action:
Fix - June 29, 2020 - FREE: JOIN OUR DEVOPS TELEGRAM GROUPS - August 2, 2019
- Review: Whizlabs Practice Tests for AWS Certified Solutions Architect Professional (CSAP) - August 27, 2018
- How to use ohai/chef-shell to get node attributes - July 19, 2018