0

I tried this:

#!/bin/bash
# addsuffix <suffix> <files>

suffix=$1
shift
for f in "$@"
do
  extension=${f##*.}
  if [ -z $extension ]; then
    mv "$f" "$f$suffix"
  else
    mv "$f" "${f%.$extension}$suffix.$extension"
  fi
done

by this command, where add_suffix is a name of previous file

sh add_suffix

but I get an error:

add_suffix: 5: shift: can't shift that many

What is wrong?

  • (1) by running sh add_suffix, you are circumventing the bash shebang (2) you are not providing any command line arguments, so there is nothing to shift (the same error can be demonstrated by sh -c 'shift') – steeldriver Apr 26 at 19:32
  • There's a bug in extension=${f##*.} which will only be an empty string ([ -z $extension ]) if file is an empty string. For file a.txt the extension will be txt, but for file a it is a. You could check [ "$f" = "$extension" ] instead. – Freddy Apr 26 at 20:16
0

I'm answering the question in the subject, not the question at the end of the post about what's wrong with the shell script.

If you are willing to do it outside of a shell script, the mmv command will do it.

me@elman:~/test$ ls
file1  file1.out  file2
me@elman:~/test$ mmv -n "*" "#1.newsuffix"
file1 -> file1.newsuffix
file1.out -> file1.out.newsuffix
file2 -> file2.newsuffix

The '-n' tells mmv to show what would be done, but not really do it (dry-run). The second argument ("*") tells mmv which files to alter (the source). You can have far more complicated match patterns, but this command should get all the non-hidden files in your directory. In the last argument "#1.newsuffix" (the destination), the #1 refers to the first wild-card match in the source specification and copies it over to the new name.

Remove the '-n' to really do the change. The manpage is very good.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.