bashstring-operations

BASH string operator syntax for retrieving filename


I'm trying to write a program that takes a file's name, and puts the date on it. So I'm trying to get substrings for the filename itself, and the extension.

I'm new to BASH so maybe I'm missing something here, but following online guides, it seems like this should work-

#!/bin/bash

echo "Type filename in this dir"
read filename
file=`filename%.*`
end=`filename##*.`
today=`date +%d-%m-%y`
dated="${file}_${today}.${end}"
cat $filename > $dated

But the computer returns these errors-

./fileDater.sh: line 5: filename%.*: command not found
./fileDater.sh: line 6: filename##*.: command not found

I'm using an Ubuntu Subsystem on Windows 10, if that's important.


Solution

  • It seems you've got some confusion about bash substitution; You're trying to execute a command sub-shell instead (eg. `variable##*.`) — it should be using ${ ... } .

    #!/bin/bash
    
    echo "Type filename in this dir"
    read -r filename
    file=${filename%.*}
    end=${filename##*.}
    today=$(date +%d-%m-%y)
    dated="${file}_${today}.${end}"
    cat "$filename" > "$dated"
    

    I haven't tried your script, although I believe that is your main issue.


    EDIT: Regarding the use of backticks (`...`)

    In the form of `COMMAND` it's more or less obsolete for Bash, since it has some trouble with nesting ("inner" backticks need to be escaped) and escaping characters.

    Use $(COMMAND) instead — it's also POSIX!

    Bash Hackers Wiki - Command Substitution