Bash脚本中mv命令报文件不存在错误(路径已验证)
Let's work through this—you’ve already confirmed the paths look correct and the files exist, so the issue is likely a subtle Bash quirk you might have missed. Here are the key fixes and checks to get your script working:
1. Always Quote Your Variables (This Is Critical!)
Even though your SRC and DST print correctly, unquoted variables in Bash get split by whitespace (including hidden characters like tabs or newlines) or expanded if they contain wildcards. This can make mv look for a partial path instead of the full file path.
Fix your mv line to use quotes around the variables:
mv -f "$SRC" "$DST"
2. Ditch eval for Safer Zero-Padded Sequence Generation
Using eval with brace expansion is risky—it can introduce unexpected hidden characters (like stray newlines or spaces) into your cam and frame values, even if they look correct when printed. Instead, use seq -w to generate zero-padded sequences cleanly:
# Replace eval-based loops with seq -w for cam in $(seq -w "$FRSTCAM" "$LSTCAM") do for frame in $(seq -w "$FRSTFRM" "$LSTFRM") do # ... rest of your code ... done done
The -w flag tells seq to pad all numbers to the same width as your starting value, so you’ll get 001, 002, ..., 012 without relying on eval.
3. Check for Hidden Control Characters
If the above fixes don’t work, verify that your variables don’t contain invisible characters. Add this line right before the mv command to inspect the exact content of SRC:
echo "$SRC" | cat -A
Look for characters like ^M (carriage returns) or extra spaces at the end of the path—these can sneak in when copying values or using eval, and they’ll break the file lookup even if the path looks correct at a glance.
Full Modified Script
Putting it all together, here’s your updated script with safer practices:
BASEPATH="/media/matt/DATA/Flow_Processing/fvv/rafa_1_ifsc/STEA_flow/" FRSTFRM=00030 LSTFRM=00270 FRSTCAM=001 LSTCAM=012 for cam in $(seq -w "$FRSTCAM" "$LSTCAM") do for frame in $(seq -w "$FRSTFRM" "$LSTFRM") do SRC="${BASEPATH}${cam}/flow/FVV_0_${cam}_${frame}_flow.flo" DST="${BASEPATH}${cam}/flow/FVV_2_${cam}_${frame}.flo" # Optional: Verify the file exists before moving if [ -f "$SRC" ]; then mv -f "$SRC" "$DST" else echo "Warning: File $SRC does not exist" fi done done
The optional if [ -f "$SRC" ] check will help you identify exactly which files are missing (if any) instead of throwing a generic error.
内容的提问来源于stack exchange,提问作者Matt Moynininhan

