0

I have a basic script to edit config files in ~/.config - it works with the cd lines, but that seems redundant:

dir=$HOME/.config/$1
if [ ! -d "$dir" ]; then :
    else 
    cd "$dir" && 
    for file in * ; do
        case "$file" in
        conf | config | *.cfg | *rc)  $EDITOR "$file" ;;
        *)  :  ;;
        esac
    done
    cd - 1>/dev/null;
fi

Changing it to use the variable "$dir" fails. What am I doing wrong?

dir=$HOME/.config/$1
if [ ! -d "$dir" ]; then :
    else 
    for file in "$dir" ; do
        case "$file" in
        conf | config | *.cfg | *rc)  $EDITOR "$file" ;;
        *)  :  ;;
        esac
    done;
fi
2
  • 1
    Why on earth do you write if [ ! -d "$dir" ]; then :; else cd "$dir" ... instead of simply if [ -d "$dir" ]; then cd "$dir" ...? Commented Jul 18, 2011 at 3:30
  • @glenn thank you: ignorance. Pure and simple. Commented Jul 18, 2011 at 4:26

3 Answers 3

1

You're not globbing the files inside $dir, merely listing $dir itself. Try $dir/*.

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

1 Comment

Precisely! Beat me to it. :-)
0

You can't use just "$dir" because that gives just a single item: the directory. You need $dir/*, but that includes the path as well, so you have to strip that off to compare just the file name:

...
for file in $dir/*; do
    filename=`basename $file`
    case $filename in
    ...

2 Comments

Thank you - that worked. Is there anything I could read up on to more fully understand this?
@Edouard: I'm afraid I can't really point you to a great resource. Most of what I know of shell scripting, I've picked up on the fly. I had to do a google search to find the "basename" command because I couldn't remember it :) Basically, the "for" iterates over all the files that come after "in". The $dir/* expands to a list of all the files that are in whatever directory "$dir" is. If $dir is /foo/bar, and that has a file named "baz" in it, then inside the loop, $file will have the value /foo/bar/baz. The basename command will strip off the path and give you "baz". Does that explain it?
0

Your first version does a * on the directory, yielding a list of all the files in the directory. Your second version just has one entry in the list --- the directory itself, not its contents.

Comments

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.