I'm getting input from file and parsing it into 2 variable. But when I run the command, I guess something is wrong with space or smt else. The command works when when I run it manually.
I have checked so many entries but couldn't find the way to do. What could be the issue.
while read p; do
echo "$p"
CRT= echo -n "$p" | awk -F '/' '{print $6}'
echo -n "$CRT"
kubectl cp ns-mv/gen-0:$p /tmp/$CRT
done < test.txt
Here is the text.txt
[master]$ cat test.txt
/opt/gen/AughGEN/OutCSY/CRT-1154.trt
[master]$
So basically what I want is
kubectl cp ns-mv/gen-0:/opt/gen/AughGEN/OutCSY/CRT-1154.trt /tmp/CRT-1154.trt as a command
output
[master]$ bash test.sh
/opt/gen/AughGEN/OutCSY/CRT-1154.trt
CRT-1154.trt
tar: /opt/gen/AughGEN/OutCSY/CRT-1154.trt\r: Cannot stat: No such file or directory
tar: Exiting with failure status due to previous errors
CodePudding user response:
The problem is that your file has Windows-style CRLF line ends, and Bash does not recognize those on Linux.
This error message:
tar: /opt/gen/AughGEN/OutCSY/CRT-1154.trt\r: Cannot stat: No such file or directory
is the hint you have to catch: it's looking for a file that ends with .trt\r
, not .trt
.
You can convert your test.txt
file to contain Linux-style LF newlines to fix the problem, or else filter the CR's as you read the file, as @vmicrobio says in a comment to another answer.
By the way, if you use Git Bash on Windows, you might notice that it can read files with CRLF and process them correctly. That's because a patch was applied just to Git Bash to allow that very common situation. But on Linux, it's treating that CR as part of the command.
CodePudding user response:
A while loop and BASH parameter expansion should be all that you need:
while read -r p ; do crt="${p##*/}"; echo kubectl cp ns-mv/gen-0:$p /tmp/$crt ; echo "/tmp/$crt" ; done <test.txt
kubectl cp ns-mv/gen-0:/opt/gen/AughGEN/OutCSY/CRT-1154.trt /tmp/CRT-1154.trt
/tmp/CRT-1154.trt
Remove the echo
from echo ubectl cp ns-mv/gen-0:$p /tmp/$crt
to execute the kubectl
commands:
while read -r p ; do crt="${p##*/}"; kubectl cp ns-mv/gen-0:$p /tmp/$crt ; echo "/tmp/$crt" ; done <test.txt
Further, as a first step in debugging, you can add a suitable shebang to your code and paste your code into shellcheck.net and implement any recommended changes.
CodePudding user response:
The command is not recognizing the space, you may use double quotes instead of single quotes to enclose the awk command, such as:
while read p; do
echo "$p"
CRT=$(echo -n "$p" | awk -F '/' '{print $6}')
echo -n "$CRT"
kubectl cp ns-mv/gen-0:$p /tmp/$CRT
done < test.txt