문제

Lo there! I have a homework where I have to ls -l any dir or file given in the arguments with the following restrictions: I have to send the whole listing to stdout then I have to tail the last 5 lines onto stderr, and finally i have to get the last line into a variable called LIST and it have to be exported. Here is my code as far as i got:

#!/bin/bash
TMP="tmp"
echo "" > $TMP
ls -l $@ >>$TMP
cat $TMP
tail -n5 $TMP 1>&2
export LIST=$(tail -n1 $TMP)

of course it doesnt work, and i dont know where did i go wrong :[ any suggestions?

도움이 되었습니까?

해결책

If you run your script that way:

$ ./script.sh

then it'll run new /bin/bash and the LIST variable will be exported to it's env.

If you run it that way:

$ . script.sh

which is a shortcut for:

$ source script.sh

Then it will execute commands from the script in the current running shell and the LIST var will be exported to its env, so you'll be able to use it later.

Your script works fine (it could be much improved but it's good enough for a simple homework task) but it exports LIST to a new shell which end its live when the script finishes.

The reason for all of this is that the child process cannot modify it's parent env. Another way to make it work is to execute one more bash at the end of your script (adding /bin/bash at the end). Then you would end-up in it with inherited LIST form the parent (the script)

If you want to improve your script than:

#!/bin/bash
TMP="tmp"              # use `mktemp` for that and `trap` to clean it even if the script will be interrupted
echo "" > $TMP         # `> $TMP` is enough to create an empty file. Another way is `touch`
ls -l $@ >>$TMP        # check Bash pitfalls webpage
cat $TMP               # you can use `tee` at the begging
tail -n5 $TMP 1>&2     # you can ommit 1 here
export LIST=$(tail -n1 $TMP)
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top