Archive for the ‘Programming’ Category

Commandline Redirection > & >>

Unix commands usually return results to the screen. Those results can be directed into a file instead, with > or >>. The first overwrites the file, the second appends to it.
ls > files_of_filenames.txt
ls >> files_of_filenames.txt

NOTE: > and >> are short forms of 1> and 1>>. 1 should be thought of as meaning stdout (Standard Output), which is almost always set to the terminal you’re typing commands on until you redirect it like this. There is also 2> and 2>> which do the same thing for stderr (Standard Error). If you don’t have permission, an error telling you so will print to stderr

To list the contents of the current folder, type the command ls. LS (in lower case letters) is short for “list” and will list the files in the current directory (like DIR on Windows).

ONE FINAL NOTE: >& 1 represents the setting where stdout is pointing.
ls 1> list.txt 2> list_errors.txt (Normal output in a file, errors in another)
ls 1> list.txt 2>& 1 (this will combine everything into one file)

This means a command like this directs to two files:
ls *  > outB.txt 2>& 1 1>outA.txt
stdout goes to outA.txt
stderr goes to outB.txt
First it sends stdout to outB.txt with > then directs stderr to where stdout is going, then redirects stdout again to outA.txt with 1> and even though there’s not reason to do this exact thing, there may be reasons in the flow of programs that “compile” pieces of a command into a final command, and this could be the result. Usually you’ll see 2>&1 with no spaces, however, I’ve added spaces to both prove it works, and to illustrate that 1 is an argument to 2>& and not just part of it.

Redirecting INPUTS
Also worth noting, there is a stdin (Standard Input) which is 0< and generally comes from the keyboard or can be from a file.
perl < list_of_inputs.txt

This is very different than command line arguments. When a script asks the user to answer a question interactively, a line from the file is read. In this way, a programmer can create a file to simulate a series of user inputs and feed it to stdin for testing.

In this example I wrote a perl script called which asks for 9 inputs in a row and prints them out once the users (or file) provides a line return (user hits enter). Here’s the script, just save it as and run perl with this file as it’s only argument as shown above. Even though the only argument to perl is and there are no arguments to the script either. The rest of the line is providing a series of inputs to the scirpt. The difference between an argument and an input is that arguments are all present at the start of the script, however, inputs are not present until the script asks for each of them.

print “Input Test Script\n”;

foreach my $idx (1..9){
$input = <stdin>;
chomp $input; #removes the line return if it’s there
print “input($idx): $input-\n”;


First Line of File.
Hi 2
Bye 3
More makes 4