![bash 문자열이 문자열을 재배치합니까? [복사]](https://linux55.com/image/12422/bash%20%EB%AC%B8%EC%9E%90%EC%97%B4%EC%9D%B4%20%EB%AC%B8%EC%9E%90%EC%97%B4%EC%9D%84%20%EC%9E%AC%EB%B0%B0%EC%B9%98%ED%95%A9%EB%8B%88%EA%B9%8C%3F%20%5B%EB%B3%B5%EC%82%AC%5D.png)
내가 직면한 문제는 명령을 저장하는 변수를 연결하면 일반 문자열과 연결할 때 문자열처럼 동작하지 않는다는 것입니다. 예는 다음과 같습니다:
base_url=$(curl -sIL --max-redirs 2 'https://hp.com' | ggrep -Po 'Location: \K(.*)$' | tail -1)
# at the time of writing this post the location is: https://www8.hp.com/us/en/home.html
test_url="https://www8.hp.com/us/en/home.html"
echo "${base_url}/subroute"
echo "${test_url}/subroute"
그런 다음 출력합니다.
/subrouteww8.hp.com/us/en/home.html
https://www8.hp.com/us/en/home.html/subroute
왜 출력이 동일하지 않은지 이해가 되지 않습니다. 이 질문이 이미 있었다면 사과드립니다. 하지만 이 문제를 다루는 다른 질문을 찾지 못했습니다.
답변1
이 활성화된 스크립트를 실행하면 명령이 캐리지 리턴과 함께 출력을 반환하는 set -x
것을 볼 수 있습니다 .curl
$ ./script.sh
++ curl -sIL --max-redirs 2 https://hp.com
++ ggrep -Po 'Location: \K(.*)$'
++ tail -1
+ base_url=$'https://www8.hp.com/us/en/home.html\r'
+ test_url=https://www8.hp.com/us/en/home.html
+ echo $'https://www8.hp.com/us/en/home.html\r/subroute'
/subrouteww8.hp.com/us/en/home.html
+ echo https://www8.hp.com/us/en/home.html/subroute
https://www8.hp.com/us/en/home.html/subroute
Bash 매개변수 확장을 사용하여 제거할 수 있습니다.
#!/bin/bash
base_url=$(curl -sIL --max-redirs 2 'https://hp.com' | ggrep -Po 'Location: \K(.*)$' | tail -1)
base_url=${base_url/$'\r'/}
test_url="https://www8.hp.com/us/en/home.html"
echo "${base_url}/subroute"
echo "${test_url}/subroute"