Edouard
Edouard

Reputation: 175

Bash variable assignment

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

Upvotes: 0

Views: 374

Answers (3)

Ryan Stewart
Ryan Stewart

Reputation: 128829

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

Upvotes: 0

Peter K.
Peter K.

Reputation: 8108

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.

Upvotes: 0

Hello71
Hello71

Reputation: 816

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

Upvotes: 1

Related Questions