Score:2

When executing a bash shell script in ubuntu 18.04, the location parameter doesn't work, how can I solve this problem?

fo flag

The name of the script is InstallmDNS.sh

The script content is as follows:

#!/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

I run the script:

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.

I run the script with parameters:

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.

I added the parameters and ran the script, but the parameters didn't do anything, what caused this? How can I fix it?

Score:4
us flag

$# in your function contains count of arguments passed to function, not to whole script. You could execute sethostname "$@" to pass all script arguments to function, then arguments count will work as you've expected.

Andrew avatar
fo flag
Thanks very much!
us flag
You are welcome :) If it works for you - please mark answer as accepted to let other people see that it solves issue.
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.