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.

[email protected]:~/code/sh/temp$ touch {1..5}
[email protected]:~/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’? [email protected]:~/code/sh/temp$ ls
[email protected]:~/code/sh/temp$

Example 2: Do not remove any files with rm

[email protected]:~/code/sh/temp$ touch {1..5}
[email protected]:~/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’? 
[email protected]:~/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.

[email protected]:~/code/sh/temp$ ls
1 2 3 4 5
[email protected]:~/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’? [email protected]:~/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, its present”
else
echo “its not present”
fi

Did not understand regular expressions, then see below links.

The following two tabs change content below.
Mr Surendra Anne is from Vijayawada, Andhra Pradesh, India. He is a Linux/Open source supporter who believes in Hard work, A down to earth person, Likes to share knowledge with others, Loves dogs, Likes photography. He works as Devops Engineer with Taggle systems, an IOT automatic water metering company, Sydney . You can contact him at surendra (@) linuxnix dot com.