재부팅하지 않고 터미널 프롬프트 호스트 이름을 "On The Fly"로 업데이트합니다.

재부팅하지 않고 터미널 프롬프트 호스트 이름을 "On The Fly"로 업데이트합니다.

호스트 이름을 변경하는 방법이나 터미널 프롬프트를 업데이트하는 방법을 묻는 것이 아닙니다. 내가 묻는 것은 사용자가 스크립트를 종료할 때 터미널 프롬프트가 업데이트되고 사용자가 명령줄에서 ~/.bashrc를 소스로 사용하거나 재부팅할 필요가 없도록 bash 스크립트에서 터미널 프롬프트를 업데이트하는 방법입니다. 새로 업데이트된 터미널 프롬프트. 내보내기와 소스로 여러 가지를 시도했지만 아무 것도 작동하지 않는 것 같습니다. 이것은 내 간단한 스크립트입니다.

 while [[ $newhostname = "" ]]; do
   printf "Use of dash \"-\" is allowed\n"
   read -p "Enter New Hostname: "  newhostname
   # Sanitize and un-tint user input
   if [[ "$newhostname" =~ ^(([a-zA-Z0-9]|[a-zA-Z0-9][\_a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][\_A-Za-z0-9\-]{0,61}[A-Za-z0-9])$  && $$
     printf "\nNew Hostname \"$newhostname\" Passes Format Criteria\n"
     hostnamectl set-hostname $newhostname
     export HOSTNAME=$newhostname
     echo 'PS1='\"\\u@${newhostname}\\w# \" >> ~/.bashrc
     source ~/.bashrc
     printf "Hostname was updated to \"$newhostname\"\n\n"
     export PS1="\u@$HOSTNAME:\w# "
   else
     printf "\nNew Hostname \"$newhostname\" Does not Pass Format Criteria allowed for DNS domain name labels\n"
     printf "http://manpages.ubuntu.com/manpages/bionic/man5/hostname.5.html\n\n"
     printf "\033[1;91m ==>> Please Try Again <<==\033[1;33m\n\n"
     newhostname=""
   fi
 done # End While

bash 스크립트에서 시스템 ENV를 변경하거나 업데이트하는 것이 불가능할까요? 어쩌면 불가능할 수도 있고, 그 일을 하려는 노력을 그만둬야 할까요? 어떤 아이디어가 있나요?

답변1

당신이 사용할 수있는PROMPT_COMMANDPS1프롬프트가 그려지기 전에 매번 변수를 업데이트하는 bash 변수 .

이렇게 하면 스크립트의 변경 사항을 ENV로 다시 전파하지 않습니다(불가능). 대신, 프롬프트를 다시 그릴 때마다 bash가 호스트 이름을 확인하도록 합니다.

다음 항목에 추가하세요 ~/.bashrc.

# set the prompt to whatever you want 
# but instead of hostname (\h) use `$dynamic_hostname` variable
PS1='\$ \u@${dynamic_hostname} : \w # '

# prompt command will update the `$dynamic_hostname` variable 
# to the latest value before each prompt redraw
PROMPT_COMMAND='dynamic_hostname=$(cat /etc/hostname)'

# this is just to make sure that `$dynamic_hostname` is not unset at any time
realtime_hostname=$(cat /etc/hostname)

프롬프트에 표시되는 호스트 이름은 를 기반으로 다시 그릴 때마다 업데이트됩니다 /etc/hostname.

물론 다른 파일이나 명령을 기반으로 호스트 이름을 업데이트할 수도 있습니다.

관련 정보