
나는 bash 스크립트를 작성 중이고 그 안에서 다음과 같은 작업을 수행하고 있습니다.
#!/bin/sh
read -p "Enter target directory: " target_dir
cp some/file.txt $target_dir/exists/for/sure/
이 쉘 스크립트를 실행하면 다음이 표시되고 입력됩니다.
./my_script.sh
Enter target directory: ~/my_dir
하지만 오류/출력이 발생합니다.
cp: directory ~/my_dir/exists/for/sure/ does not exist
그리고 분명히 밝히고 싶은 것은 해당 디렉토리가 100% 존재한다는 것입니다. 즉, 오류 없이 다음을 실행할 수 있습니다.
cd ~/my_dir/exists/for/sure/
여기서 무슨 일이 일어나고 있는 걸까요?
답변1
문제는 ~
에 대한 입력으로 입력할 때 문자 그대로 받아들여지고 확장되지 않는다는 것입니다 read
.
테스트해보세요:
$ read target
~
$ ls $target
ls: cannot access '~': No such file or directory
(참고, 주위의 따옴표 ~
)
eval target=$target # unsafe
이상이지만 다음과 같이 확장됩니다 ~
.
target="${target/#\~/$HOME}"
read
또는 더 나은 방법은 처음부터 변수 등을 입력하지 않는 것입니다 .