Run bash script remotely with multiple arguments through curl

Hi all!

How ca I modify this bash script so that I can execute it with multiple arguments? For the moment it works only with one argument at a time. I really appreciate your help!

#!/bin/bash

function show_usage (){
    printf "Options:\n"
    printf " -m|--moon, Print moon\n"
    printf " -e|--earth Print earth\n"
    printf " -h|--help, Print help\n"

return 0
}


moon(){
echo "moon"
}

earth(){
echo "earth"
}

help(){
echo "help"
}

while [ ! -z "$1" ]; do
  case "$1" in
     --moon|-m)
         shift
         moon
         ;;
     --earth|-e)
         shift
         earth
         ;;
     --help|-h)
        shift
        help
         ;;
     *)
        show_usage
        ;;
  esac
shift
done

I am running the bash script like this:

 curl -sSL https://remote-server.com/bash-script.txt | bash -s -- -e -m

It executes only the first argument.

We often process script options using the getopts statement. For example:

#!/bin/bash
USAGE="usage: $0 -e -m -h"
while getopts :emh opt_char
do
case $opt_char in
	e) echo "earth";;
	m) echo "moon";;
	h) echo "$USAGE";;
	\?)
	echo "$OPTARG is not a valid option."
	echo "$USAGE";;
esac
done

This should work.

Thank you! The script works great. I am just wondering if it is possible to add also long name for arguments like: -earth , -moon , -help

No. The getopts (note s in getopts) Bash builtin only support short option.

If you want a long option, use the getopt(1) {getopt(1) — util-linux — Debian stretch — Debian Manpages} command on Linux from GNU. GNU/getopt only works on Linux and not on BSD or macOS, or any other version. So there is that issue.

getopt(1) example {external command}

#!/bin/bash

# -o short option
# -l long option
TEMP=$(getopt -o 'meh' -l 'moon,earth,help' -- "$@")
USAGE="usage: $0 -e -m -h --moon --earth --help"

# usage/error
if [ $? -ne 0 ]; then
	echo "$USAGE" >&2
	exit 1
fi

# Note the quotes around "$TEMP": they are essential!
eval set -- "$TEMP"
unset TEMP

while true; do
	case "$1" in
		'-m'|'--moon')
			echo 'MOON'
			shift
			continue
		;;
		'-e'|'--earth')
			echo "Earth"
			shift 
			continue
		;;
		'-h'|'--help')
			echo "$USAGE" >&2
			shift 
			continue
		;;
		'--')
			shift
			break
		;;
		*)
			echo 'Error' >&2
			exit 1
		;;
	esac
done

If I were you, I would stick with getopts as it works with BASH or KSH and has more excellent compatibility across Unix-like systems when using Bash. But, it is your choice. Let me know if this solves your issue.

1 Like

This is the solution I was looking for. Per your advice I will stick with getopts . Thank you very much for helping me. :partying_face: :partying_face: :partying_face: