0

I want the user to be able to name a file to be created, and then have the output of the script redirected to that file. The script will create a long listing of a directory and count the number of files in that directory. This is what I have so far:

echo -n "Please enter the name of a file to be created: "

read FILENAME

touch FILENAME

ls -l exampledir

echo

ls -l exampledir | wc -l

I might not be using read correctly, I'm not too sure.

Edit

I figured most of it out, here is the new code:

echo -n "Please enter the name of a file to be created: "

read FILENAME

ls -l Assign_7 > FILENAME

echo >> FILENAME

ls -l Assign_7 | wc -l >> FILENAME

The only thing I can't figure out is how to get the file to be named what the user entered. It has the right stuff inside, but right now the file is always called FILENAME

2nd EDIT

Figured it out. Just needed to add $ before each FILENAME

0

1 Answer 1

1

Quite simple:

#/bin/bash
echo -n "Please enter the name of a file to be created: "

read FILENAME

ls -l Assign_7 > $FILENAME
echo >> $FILENAME
ls -l Assign_7 | wc -l >> $FILENAME

This is called Parameter Expansion, see man bash for complete explanation.

Also, there is a bit shorter form that simplifies the script a bit and makes the bash to open an output file only once:

#/bin/bash
echo -n "Please enter the name of a file to be created: "

read FILENAME

exec > $FILENAME
ls -l Assign_7
echo ""
ls -l Assign_7 | wc -l

This latter form does redirection of the current shell's stdout to a file by executing exec > $FILENAME command, thus the output of all subsequent commands the shell executes is also directed to that file.

Not the answer you're looking for? Browse other questions tagged .