Dan
Dan

Reputation: 378

how to print the ouput/error to a text file?

I'm trying to redirect(?) my standard error/output to a text file. I did my research, but for some reason the online answers are not working for me. What am I doing wrong?

cd /home/user1/lists/

for dir in $(ls)
do
(
echo | $dir > /root/user1/$dir" "log.txt
) > /root/Desktop/Logs/Update.log
done

I also tried

2> /root/Desktop/Logs/Update.log
1> /root/Desktop/Logs/Update.log
&> /root/Desktop/Logs/Update.log

None of these work for me :(

Help please!

Upvotes: 0

Views: 89

Answers (2)

tripleee
tripleee

Reputation: 189377

If you are trying to obtain a list of the files in /home/user1/lists, you do not need a loop at all:

ls /home/usr1/lists/ >Update.log

If you are attempting to run every file in the directory as an executable with a newline as its input, and collect the output from all these programs in Update.log, try this:

for file in /home/user1/lists/*; do
    echo | "$file"
done >Update.log

(Notice how we avoid the useless use of ls and how there is no redirection inside the loop.)

If you want to create an empty file called *.log.txt for each file in the directory, you would do

for file in /home/user1/lists/*; do
    touch "$(basename "$file")"log.txt
done

(Using basename to obtain the file name without the directory part avoids the cd but you could do it the other way around. Generally, we tend to avoid changing the directory in scripts, so that the tool can be run from anywhere and generate output in the current directory.)

If you want to create a file containing a single newline, regardless of whether it already exists or not,

for file in /home/user1/lists/*; do
    echo >"$(basename "$file")"log.txt
done

In your original program, you redirect the echo inside the loop, which means that the redirection after done will not receive any output at all, so the created file will be empty.

These are somewhat wild guesses at what you might actually be trying to accomplish, but should hopefully help nudge you slightly in the right direction. (This should properly be a comment, I suppose, but it's way too long and complex.)

Upvotes: 0

Gary_W
Gary_W

Reputation: 10360

Try this for the basics:

echo hello >> log.txt 2>&1

Could be read as: echo the word hello, redirecting and appending STDOUT to the file log.txt. STDERR (file descriptor 2) is redirected to wherever STDOUT is being pointed. Note that STDOUT is the default and thus there is no "1" in front of the ">>". Works on the current line only.

To redirect and append all output and error of all commands in a script, put this line near the top. It will be in effect for the length of the script instead of doing it on each line:

exec >>log.txt 2>&1

Upvotes: 1

Related Questions