Sep 05 2009

How to automatically provide an answer to Unix commands

Published by at 4:29 pm under Unix/Linux

How do you automatically provide an answer to a Unix command for example

cp: overwrite `destination/./b.txt'?

Many Unix/Linux commands that operate on files may stop and ask for confirmation for each file before completing an action. Of course for many Unix/Linux commands there are parameters that allows you to specify the desired behavior, but there are other commands that doesn’t have that capability. Advanced Unix users just look up the “yes” command on how to solve this. Here’s a contrived example where a directory called “destination” contains two files “a.txt” and “b.txt”. We will now copy two files “b.txt” and “c.txt” from a directory called “source”

|-- destination
|   |-- a.txt
|   `-- b.txt
`-- source
 |-- b.txt
 `-- c.txt

We’ll copy the files using the “cp” command

cp source/*.txt destination/.

When we do this we’ll get the following response on the command line where the OS is asking us what it want us to do since one file being copied already exist in the destination directory i.e. “b.txt”

cp: overwrite `destination/./b.txt'?

Unfortunately on Linux the cp command doesn’t have an option to automatically answer this question with a ‘y’ or ‘n’ answer. There’s more than one solution to this problem depending on what you want to do, and one solution is to use the Unix “yes” command. This command will output a string repeatedly until killed. If we want to avoid overwriting any of the files in the destination directory we could use the “yes” command to answer all questions with a no “n”. Below you can see how the “yes” command is used to automatically provide the answer “n” to the “cp” command. Use “man yes” for more information about the “yes” command.

yes n | cp source/*.txt destination/.

This successfully copies all files with the exception of the “b.txt” file which is what we wanted. The “yes” command automatically provided the answer “n” to the “cp” command question whether or not we wanted to overwrite the destination file.

In the case that you mess up when you use the “yes” command for example by typing this:

yes bingo

The “yes” command will output the word “bingo” repeatedly to the screen. You can stop it by typing Control-C or in a different shell type “pgrep yes” which will display the “yes” commands PID (process ID) which you can use to kill the “yes” command by typing “kill <PID>”

pgrep yes

In my case it returned 24940 so I killed it with:

kill 24940

One response so far

One Response to “How to automatically provide an answer to Unix commands”

  1. chawlee says:

    absolutely useful. i always pipe “yes” the wrong way and never get my files copied. rather annoying.

    does the yes command eventually stop when the copy is done? i suppose I could test it out but i’m already leaving the comment. =D

Leave a Reply