ubuntu 18.04에서 bash 쉘 스크립트를 실행할 때 위치 매개변수가 작동하지 않습니다. 이 문제를 해결하는 방법은 무엇입니까?

ubuntu 18.04에서 bash 쉘 스크립트를 실행할 때 위치 매개변수가 작동하지 않습니다. 이 문제를 해결하는 방법은 무엇입니까?

스크립트 이름은 InstallmDNS.sh입니다.

스크립트 내용은 다음과 같습니다.

#!/bin/bash

sethostname() {
  if [ $# -eq 1 ]
  then
    hostnamectl set-hostname "$1"
    sed -i "/127.0.1.1/d" /etc/hosts
    sed -i "/127.0.0.1/a\127.0.1.1    $1" /etc/hosts
    reboot
  else
    echo "The exapmle of execute the script:  bash InstallmDNS.sh server1"
    echo "This script is executed with one parameter."
    exit 0
  fi
}

dia=`systemctl status avahi-daemon|grep Active`
if [[ "$dia" =~ "running" ]]
then
  echo "mDNS is running"
  sethostname
else
  apt-get install avahi-daemon -y
  echo "mDNS installation complete."
  sethostname
fi

스크립트를 실행합니다.

root@linux:/home/ankon# bash InstallmDNS.sh
mDNS is running
The exapmle of execute the script:  bash InstallmDNS.sh server1
This script is executed with one parameter.

매개변수를 사용하여 스크립트를 실행합니다.

root@linux:/home/ankon# bash InstallmDNS.sh server2
mDNS is running
The exapmle of execute the script:  bash InstallmDNS.sh server1
This script is executed with one parameter.

매개변수를 추가하고 스크립트를 실행했지만 매개변수가 아무 작업도 수행하지 않았습니다. 이 문제의 원인은 무엇입니까? 어떻게 해결할 수 있나요?

답변1

매개변수를 스크립트에 전달하는 것은 매개변수를 스크립트 내의 함수에 전달하는 것과 다릅니다.

스크립트에 제공된 매개변수는 함수에 "자동으로 전달"되지 않습니다.

server2$1 이 스크립트에 전달된 값일 것으로 예상했지만 실제로는 함수를 호출할 때 함수에 어떤 인수도 전달하지 않았습니다.

if [[ "$dia" =~ "running" ]]
then
  echo "mDNS is running"
  sethostname <---- This line should pass the arguments
else
  apt-get install avahi-daemon -y
  echo "mDNS installation complete."
  sethostname <---- This line should pass the arguments
fi

표시된 줄은 다음으로 변경되어야 합니다.

sethostname $1

관련 정보