简体   繁体   中英

How can I compare two strings in bash?

I am trying to remove all ".s" files in a folder that can be derived by ".c" source files. This is my code

for cfile in *.c; do 
    #replace the last letter with s
    cfile=${cfile/%c/s}
    for sfile in *.s; do
        #compare cfile with sfile; if exists delete sfile
        if [ $cfile==$sfile ]; then
            rm $sfile;
        fi
    done
done

But this code deletes all the ".s" files. I think it's not comparing the filenames properly. Can someone please help.

The canonical way to compare strings in bash is:

if [ "$string1" == "$string2" ]; then

this way if one of the strings is empty it'll still run.

You can use it like this:

[[ "$cfile" = "$sfile" ]] && rm "$sfile"

OR

[[ "$cfile" == "$sfile" ]] && rm "$sfile"

OR by using old /bin/[ (test) program

[ "$cfile" = "$sfile" ] && rm "$sfile"

Saying

if [ $chile==$sfile ]; then

would always be true since it amounts to saying

if [ something ]; then

Always ensure spaces around the operators.

The other problem is that you're saying:

cfile=${cfile/%c/s}

You probably wanted to say:

sfile=${cfile/%c/s}

And you need to get rid of the inner loop:

for sfile in *.s; do
done

Just keep the comparison code.

I think the most simpliest solution would be:

for cfile in *.c ; do rm -f "${cfile%.c}.s" ; done

It just lists all the .c files and try to delete the corresponding .s file (if any).

for cFile in *.c; do
    sFile="${cFile%c}s"
    if [[ -f "$sFile" ]]; then
        echo "delete $sFile"
    fi
done

The actual deletion of the files I leave as an exercise. :-)

You can also just brute force and delete everything and redirecting the error messages to /dev/null :

for cFile in *.c; do
    sFile="${cFile%c}s"
    rm "$sFile" &> /dev/null
done

but this will be slower of course.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM