0

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!

1
  • 2
    You could just write to stdout and let the user redirect wherever they want: ./Tree ./* > README. That way they could view the output on screen or pipe it to less or what have you. Commented Oct 21, 2015 at 18:04

2 Answers 2

3

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).

Sign up to request clarification or add additional context in comments.

Comments

2

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

2 Comments

You should probably advise using "$@" and "$i".
If I just only want to put the output file in the last ,What should I do?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.