Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I have a script for school that mimics the cp command. Part of the assignment is to modify the script so that the while loop (that assigns stdin to the variable filelist) is instead done with sed.

The last argument needs to be saved to variable to because that could be a directory depending on other user input in the script.

while [ "$#" -gt 1 ]
do
        filelist="$filelist $1"
        shift
done

to="$1"

The finished product is below. Is that good? How could I polish it up?

filelist=$(echo $* | sed 's/ [^ ]*$//')
to=$(echo $* | sed 's/^.* \([^ ]*\)$/\1/')
share|improve this question
    
The while loop produces different output, " 1 2 3" vs. "1 2 3" by the sed call. –  ferada Dec 5 '14 at 13:52
    
The sed version assumes each argument is only one "word". If the last argument has spaces in it your version fails. (To be fair though I don't know that with sed you can do better than that easily and robustly.) –  Etan Reisner Dec 5 '14 at 16:36
1  
Also there's no reason to use sed for the to assignment. len=$#; to=${!len} or len=$#; a=("$@"); to=${a[$# - 1]}. –  Etan Reisner Dec 5 '14 at 16:39

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.