简体   繁体   中英

mv: missing file operand while using mv in shell script but not in terminal

I am trying to write a shell script that the user inputs what file they would like to rename as the first variable, then what they want the new name to be for it's second variable. The only output the program will give is that mv is missing file operand. I've hit a wall and am out of things to try at this point. I have tried using absolute paths to the file, which did not help. Google has turned up nothing for me.

The mv works as expected in the command line but as soon as variables are introduced the program goes kaput. I have tried every way of formatting my input possible.

#!/bin/bash
echo -n "Original filename: "
read $input_filename
echo ""
echo -n "New filename: "
read $output_filename
echo ""
mv -v $input_filename  $output_filename
if [ $? == 0 ]
then
echo "Task completed successfully"
else
    echo "ERROR: File failed to be renamed. Exiting."
fi

Output and related file contents.

davevm@davevm-VirtualBox:~/lab10$ ls
helloworld  lab10.sh
davevm@davevm-VirtualBox:~/lab10$ ./lab10.sh 
Original filename: helloworld

New filename: copy1

mv: missing file operand
Try 'mv --help' for more information.
ERROR: File failed to be renamed. Exiting.

The read builtin command takes a variable name as its argument.

Use read filename , not read $filename .

You should also quote the arguments to the mv command:

mv -v "$input_filename" "$output_filename"

When debugging shell scripts, it is often useful to add the line set -x to the top of the file, which will output all commands as they are executed to show exactly what is happening. With your script, doing that reveals this output:

+ mv -v
mv: missing file operand

Hmm, it looks like your $input_filename and $output_filename vars aren't being set. Looking up the docs for read , the error becomes apparent. You should not prefix variable names with a $ when setting them, so read $input_filename becomes read input_filename , and the same for reading the output filename

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