-3
for f in $* 
do
mv common.txt corporate.txt
done

Is it right??

AdminBee
  • 22,803
  • 1
    Welcome to the site. Apart from some syntax errors (which I corrected), your for loop will iterate over all command-line arguments, but for everyone execute the same rename command from common.txt to corporate.txt which must fail already after the first such iteration and is unlikely what you want. If your aim really is to simply rename this one file, you can just execute the mv command and inspect the return value, $?. If it is 0, the command was executed successfully; if non-zero, you will know that an error has occured. – AdminBee Feb 28 '20 at 13:07

2 Answers2

1

If you are only renaming a single file there is no need to loop over all positional parameters, however if you do loop over all positional parameters you should use:

for f in "$@"; do

$@ when double quoted will allow you to have parameters that contain spaces without being subject to word splitting and is generally more robust for multiple reasons.


On to your script, mv common.txt corporate.txt will rename the file as per the parameters (given the common.txt file exists within the same directory as the script) but you are performing no check to ensure it was renamed. Personally I would point to the full path of the file though and perhaps use this is a learning experience for a few slightly unnecessary additions:

And some necessary additions:


Using all this you could create a script like:

#!/bin/sh

file=/path/to/common.txt
path=$(dirname "$file")

if mv "$file" "${path}/corporate.txt"; then
    printf '%s\n' "${file}: renamed successfully" >&2
else
    printf '%s\n' "Failed to move: $file" >&2
fi
jesse_b
  • 37,005
-1

if mv common.txt corporate.txt; then echo "Success"

vonbrand
  • 18,253