Zhang Tao
Zhang Tao

Reputation: 23

Script redirect command output to last filename argument

File name:Tree(executable)

#!/bin/bash
for i in $*
do
    if [ -d $i ]; then

        echo "===================$i================" >> ????? 
        tree -L 1 $i >> ?????
    fi
done

As you see, I want to list the tree structure of the parameters that I input,I want to let all the tree structure redirect to the last file(it's id is $#),it is "?????" in this script,because I do not know how to write it.

For example:

./Tree ./* README

YES,all directory tree structure will write in README!

Upvotes: 0

Views: 66

Answers (2)

chepner
chepner

Reputation: 532053

It would be better to put the name of the output file first, so that it doesn't interfere with the variable-length list of files you iterate over:

#!/bin/bash
output=$1
shift

for i in "$@"; 
do
    if [ -d "$i" ]; then

        echo "===================$i================" 
        tree -L 1 "$i"
    fi
done > "$output"

Then call your script as

./Tree README ./*

Better yet, there's really no need to pass the name of the output file to the script; just let the script write to standard output and do the redirection outside.

./Tree ./* > README

Upvotes: 2

Etan Reisner
Etan Reisner

Reputation: 81012

It would be easier/simpler to do this if your output file was the first argument instead of the last.

That would just need

output=$1
shift

added to the top of the script.

Using the last argument isn't harder really it just involves more "advanced" variable usage:

#!/bin/bash
output="${@: -1}"

for i in "${@:0:${#@}}"
do
    if [ -d "$i" ]; then

        echo "===================$i================" >> "$output"
        tree -L 1 "$i" >> "$output"
    fi
done

Where "${@: -1}" is the last element in the array of arguments and "${@:0:${#@}}" is the arguments from 0 to ${#@} (the length of $@ which is the count of arguments to the script).

Upvotes: 3

Related Questions