Capture user input bash if/then/elif - bash

I'm trying to create a simple script for logging into various servers via ssh, all keys have been installed and are working but i simply cannot get this script to work for me. Basically there is an option as to which server the user wishes to login to but it keeps throwing up the following error:
': not a valid identifier `INPUT
login.sh: line 24: syntax error near unexpected token `elif'
'ogin.sh: line 24: `elif [ $INPUT -eq 2 ] ; then
The script layout can be found below with dummy info:
#!/bin/bash
echo "What Server would you like to login to?"
echo ""
echo ""
echo "1. Server 1"
echo "2. Server 2"
echo "3. Server 3"
echo "4. Server 4"
echo "5. Exit"
read INPUT
if [ $INPUT -eq 1 ] ; then
echo"Logging in"
echo"..."
ssh root#1.2.3.4 -p 5678
elif [ $INPUT -eq 2 ] ; then
echo"Logging in"
echo"..."
ssh root#1.2.3.4 -p 5678
elif [ $INPUT -eq 3 ] ; then
echo"Logging in"
echo"..."
ssh root#1.2.3.4 -p 5678
elif [ $INPUT -eq 4 ] ; then
echo"Logging in"
echo"..."
ssh root#1.2.3.4 -p 5678
elif [ $INPUT -eq 5 ] ; then
exit 0
else
echo "invalid choice"
return
fi
Any help would be greatly appreciated, relatively new to using bash and this is just annoying me now!

looks like you created this file on windows.
try, using dos2unix like:
dos2unix <your_script>

This answer is really just a comment, but comments are not suitable for code. You're script could be greatly simplified. Consider something like:
#!/bin/bash
servers=( host1 host2 host3 )
ips=( 192.168.1.1 192.168.1.2 192.168.1.3 )
ports=( 123 22 33 )
select server in ${servers[#]}; do
echo "Logging into $server..."
ssh root#${ips[$REPLY]} -p ${ports[$REPLY]}
break
done
(Although it's not at all clear why you would want to specify the IP addresses rather than using the hostname!)

Tried your script by copy pasting, it worked. I modified a little more on it to get the invalid choice option to work.
Errm... sorry, but it works for me?
#!/bin/bash
while true ; do
echo "What Server would you like to login to?"
echo ""
echo ""
echo "1. Server 1"
echo "2. Server 2"
echo "3. Server 3"
echo "4. Server 4"
echo "5. Exit"
read INPUT
if [ $INPUT -eq 1 ] ; then
echo "Logging in 1"
echo "..."
ssh root#1.2.3.4 -p 5678
elif [ $INPUT -eq 2 ] ; then
echo "Logging in 2"
echo "..."
ssh root#1.2.3.4 -p 5678
elif [ $INPUT -eq 3 ] ; then
echo "Logging in 3"
echo "..."
ssh root#1.2.3.4 -p 5678
elif [ $INPUT -eq 4 ] ; then
echo "Logging in 4"
echo "..."
ssh root#1.2.3.4 -p 5678
elif [ $INPUT -eq 5 ] ; then
exit 0
else
echo "invalid choice"
fi
done

I'll throw myself in front of the SO bus by answering the question you didn't ask on this one. Why not use select?
echo 'Which server would you like to log into?'
select server in 192.168.0.1 192.168.0.2 192.168.0.3 192.168.0.4; do
printf 'Logging in to server %s...\n' "$server"
ssh "$server" -p "$port"
done
If you don't like select, then why not at least use case?
read -p 'Which server do you want? ' input
case "$input" in
whatever)
printf 'Logging in to server %s...\n' "$server"
ssh "$server" -p "$port"
;;
*)
echo 'Invalid option'
;;
esac

I realize this doesn't answer your question, but you said you were new to bash. I'd suggest using the case statement instead of a mess of ifs and I also added a prompt to your read statement (with the -p option). You might also look into the select statement instead of the case.
#!/bin/bash
echo "What Server would you like to login to?"
echo ""
echo ""
echo "1. Server 1"
echo "2. Server 2"
echo "3. Server 3"
echo "4. Server 4"
echo "5. Exit"
read -p "cmd> " INPUT
case $INPUT in
1)
echo "Logging in"
echo "..."
echo ssh root#1.2.3.4 -p 5678
;;
2)
echo "Logging in"
echo "..."
echo ssh root#1.2.3.4 -p 5678
;;
3)
echo "Logging in"
echo "..."
echo ssh root#1.2.3.4 -p 5678
;;
4)
echo "Logging in"
echo "..."
echo ssh root#1.2.3.4 -p 5678
;;
5)
echo "exiting"
exit 0
;;
*)
echo "invalid choice"
return
;;
esac

Related

Bash script syntax error: unexpected end of file [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
im trying to create a simple bash script to create and delete a user on ubunutu , here is my script
sudo nano createuser.sh
#!/bin/bash
choice=2
# Main Display
echo "Enter Number to select an option"
echo
echo "1) Add User"
echo "2) Delete User"
echo
while [ $choice -eq 2 ]; do
read choice
if [ $choice -eq 1] ;
then
echo -e "Enter Username"
read user_name
echo -e "Enter Password"
read user_passwd
sudo useradd $user_name -m -p $user_passwd
cat /etc/passwd
else if [$choise -eq 2] ; then
cat /etc/passwd
echo -e "Enter Password"
read del_passwd
echo -e "User to be deleted:"
read del_user
sudo userdel -r $del_user
cat /etc/passwd
echo
fi
im not sure if there s a typo on my script ,or something else .
whenever i execute the script i get this message
Enter Number to select an option
Add User
Delete User
./createuser.sh: line 31: syntax error: unexpected end of file
thank you in advance for your help !!
Errors:
wrong if/else/fi sequence, what you have is basically this w few errors
if [ ]
then
# something
else
if [ ]
then
# something else
fi
# fi should be here ti close outer if []
In bash you have if then/elif/else closed by fi So something like this
if []
then
# something
elif []
then
# something else happened
else
# something else than elif happened
fi
; after if [], it only goes there if if and than are in the same line, like so
if [] ; then
# something
elif []
# something else happened
else
# something else than elif happened
fi
space inside test brackets []
if [ a -eq 5 ]
# ^ ^
# +-------+----< notice space here
In bash while sequence goes as following while [ ] do done. like following
while [ i -le 55 ]
do
# do something
done
Suggestions
use -s for reading in password in bash to hide it while typing.
Conclusion, with all the fixes above here is working script:
#!/bin/bash
choice=2
# Main Display
echo "Enter Number to select an option"
echo
echo "1) Add User"
echo "2) Delete User"
echo
while [ $choice -eq 2 ]
do
read choice
if [ $choice -eq 1 ]
then
echo -e "Enter Username"
read user_name
echo -e "Enter Password"
read user_passwd
sudo useradd $user_name -m -p $user_passwd
cat /etc/passwd
elif [ $choise -eq 2 ]
then
cat /etc/passwd
echo -e "Enter Password"
read del_passwd
echo -e "User to be deleted:"
read del_user
sudo userdel -r $del_user
cat /etc/passwd
echo
else
echo "Wrong option you have 1 or 2"
fi
done
yes guys ,thank you so much for your help
i just fixed it
here is my working script now
#!/bin/bash
choice=2
# Main display echo "Enter number to select an option" echo echo "1) Add User" echo "2) Delete User" echo
while [[ "$choice" -eq 2 ]]; do
read choice
if [[ "$choice" -eq 1 ]] ; then
echo -e "Enter Username"
read user_name
echo -e "Enter Password"
read user_passwd
sudo useradd "$user_name" -m -p "$user_passwd"
cat /etc/passwd else
if [[ "$choice" -eq 2 ]] ; then
cat /etc/passwd
echo
echo -e "User to be deleted:"
read del_user
sudo userdel -r "$del_user"
cat /etc/passwd
echo
choice=2
fi
fi
done

Shell script error: Syntax error: "(" unexpected (expecting "fi")

I am getting a syntax error with the following shell script and I just can't figure out why:
./query_certs.sh: 22: ./query_certs.sh: Syntax error: "(" unexpected (expecting "fi")
Is it because of nested if-else statements?
Thanks in advance.
# Check how many arguments we received
if [ "$#" -gt 2 ]; then
echo "Usage: $0 [MODE] DESTINATION_IP" >&2
echo "MODE may be one of the following" >&2
echo "none - shell script will ask interactively" >&2
echo "HTTP - query the certificate from HTTPS (port 443)" >&2
echo "LDAP - query the certificate from an AD (port 636" >&2
echo "FTP - query the certificate from an FTPs (ports 990/989)" >&2
exit 1
elif [ "$#" == 2 ]; then
MODE=$1
if [ "$MODE" == "HTTP" ]; then
QUERY="foo"
elif [ "$MODE" == "LDAP" ]; then
QUERY="bar"
elif [ "$MODE" == "FTP" ]; then
QUERY="baz"
else
echo "Please choose a mode (HTTP | LDAP | FTP):" # <<< that's line 22
options=("HTTP" "LDAP" "FTP";)
select opt in "${options[#]}" do
case $opt in
"HTTP")
echo "Selected HTTP"
;;
"LDAP")
echo "Selected LDAP"
;;
"FTP")
echo "Selected FTP"
;;
esac
done
fi
fi
Ok, I fixed it myself. One important thing I didn't mention in my original post (added it now so it might be helpful for others): initially I had the following shebang:
#!/usr/bin/env sh
As I wanted to have POSIX conform. Seems like some routines I am using aren't POSIX conform. Hence, I changed to using bash. Furthermore, there were more mistakes, which are fixed as follows:
# Check how many arguments we received
if [ "$#" -gt 2 ]; then
echo "Usage: $0 [MODE] DESTINATION_IP" >&2
echo "MODE may be one of the following" >&2
echo "none - shell script will ask interactively" >&2
echo "HTTP - query the certificate from HTTPS (port 443)" >&2
echo "LDAP - query the certificate from an AD (port 636" >&2
echo "FTP - query the certificate from an FTPs (ports 990/989)" >&2
exit 1
elif [ "$#" = 2 ]; then
MODE=$1
if [ "$MODE" = "HTTP" ]; then
QUERY="foo"
elif [ "$MODE" = "LDAP" ]; then
QUERY="bar"
elif [ "$MODE" = "FTP" ]; then
QUERY="baz"
else
PS3='Please choose a mode (HTTP | LDAP | FTP):'
options=("HTTP" "LDAP" "FTP")
select opt in "${options[#]}" do
case $opt in
"HTTP")
echo "Selected HTTP"
;;
"LDAP")
echo "Selected LDAP"
;;
"FTP")
echo "Selected FTP"
;;
esac
done
fi
fi

Bash script to chose based on user input

Problem:
I need to make this bash script to choose based on the user inputs. Example how can i add choices? such that user just select from 1 to 3 and that is set in variable CLUSTER_NAME.
choices are test.com, try.com and me.com
Script
#!/bin/bash
sops_ops() {
sops --version
if [ "$?" -eq "0" ]; then
echo "proceed sops ops"
else
echo "check sops binary"
fi
read -p 'Enter cluster_NAME: = ' CLUSTER_NAME
test_environment="test.com"
test1_environment="test1.com"
test2_environment="test2.com"
case "${$CLUSTER_NAME}" in
prod.$test_environment) ;;
dev.$test1_environment) ;;
stage.$test2_environment) ;;
test.$test_environment) ;;
*) echo "Invalid option: ${CLUSTER_NAME}" 1>&2 && exit 1 ;;
if [ $CLUSTER_NAME = test.$test_env ];then
printf "got cluster $CLUSTER_NAME"
elif [ $CLUSTER_NAME = "test.test.com" ];then
printf "got dev cluster $CLUSTER_NAME"
echo "not found cluster"
else
echo "Environment not available"
fi
}
sops_ops
Question:
How do I do that?
Any help is appreciated!

assign number value to alphabet in shell/bash

I have a script that prompts for the user to enter a 3 letter code. I need to convert that code to a number that corresponds to a=01, b=02....etc for the first two letters of that code.
For example the user enters ABC for $SITECODE I need to take the A&B and convert it to 0102 and store it to a new variable.
#!/bin/bash
# enable logging
exec 3>&1 4>&2
trap 'exec 2>&4 1>&3' 0 1 2 3
exec 1>/var/log/ULFirstBoot.log 2>&1
###################################### global variables ######################################################
# top level domain
tld="somedomain.com"
# grabs the serial number for ComputerName
serial=`/usr/sbin/system_profiler SPHardwareDataType | /usr/bin/awk '/Serial\ Number\ \(system\)/ {print $NF}'`
# Cocoadialog location
CD="/Users/Shared/cocoaDialog.app/Contents/MacOS/cocoaDialog"
################################################### Begin Define Functions ####################################################
userinput () # Function will promt for Username,SItecode, and Region using Cocoadialog
{
# Prompt for username
rv=($($CD inputbox --title "User Name" --no-newline --informative-text "Please Enter the Users Employee ID" --icon "user" --button1 "NEXT" --button2 "Cancel"))
USERNAME=${rv[1]}
if [ "$rv" == "1" ]; then
echo "`date` User clicked Next"
echo "`date` Username set to ${USERNAME}"
elif [ "$rv" == "2" ]; then
echo "`date` User Canceled"
exit
fi
# Dialog to enter the User name and the create $SITECODE variable
rv=($($CD inputbox --title "SiteCode" --no-newline --informative-text "Enter Site Code" --icon "globe" --button1 "NEXT" --button2 "Cancel"))
SITECODE=${rv[1]} #truncate leading 1 from username input
if [ "$rv" == "1" ]; then
echo "`date` User clicked Next"
echo "`date` Sitecode set to ${SITECODE}"
elif [ "$rv" == "2" ]; then
echo "`date` User Canceled"
exit
fi
# Dialog to enter the Password and the create $REGION variable
rv=($($CD dropdown --title "REGION" --text "Choose Region" --no-newline --icon "globe" --items NA EULA AP --button1 "OK" --button2 "Cancel"))
item=${rv[1]}
if [[ "$rv" == "1" ]]
then echo "`date` User clicked OK"
elif [[ "$rv" == "2" ]]
then echo "`date` User Canceled"
exit
fi
if [ "$item" == "0" ]; then
REGION="NA"
echo "`date` Region set to NA"
elif [ "$item" == "1" ]; then
REGION="EULA"
echo "`date` Region set to EULA"
elif [ "$item" == "2" ]; then
REGION="AP"
echo "`date` Region Set to AP"
fi
# Confirm that settings are correct
rv=($($CD msgbox --text "Verify settings are correct" --no-newline --informative-text "USER-$USERNAME REGION-$REGION, SITE CODE-$SITECODE" --button1 "Yes" --button2 "Cancel"))
if [[ "$rv" == "1" ]]
then echo "`date` User clicked OK"
elif [[ "$rv" == "2" ]]
then echo "`date` User Canceled"
exit
fi
}
# Sets computername based
setname ()
{
ComputerName=$SITECODE$serial
/usr/sbin/scutil --set ComputerName $SITECODE$serial
echo "`date` Computer Name Set to" $(/usr/sbin/scutil --get ComputerName)
/usr/sbin/scutil --set LocalHostName $SITECODE$serial
echo "`date` LocalHostname set to" $(/usr/sbin/scutil --get LocalHostName)
/usr/sbin/scutil --set HostName $SITECODE$serial.$tld
echo "`date` Hostname set to" $(/usr/sbin/scutil --get HostName)
}
adbind ()
{
OU="ou=Computers,ou=${SITECODE}Win7,ou=$REGION,dc=global,dc=ul,dc=com"
echo "`date` OU will be set to $OU"
dsconfigad -add "global.ul.com" -username "user" -password "password" -ou "$OU"
dsconfigad -mobile "enable" -mobileconfirm "disable" -groups "Domain Admins, ADMIN.UL.LAPTOPADMINS"
}
# Checks if machine is succesfully bound to AD before proceeding
adcheck ()
{
until [ "${check4AD}" = "Active Directory" ]; do
check4AD=`/usr/bin/dscl localhost -list . | grep "Active Directory"`
sleep 5s
done
}
adduser () # creates mobile user account based on userinput function
{
# create mobile user account and home directory at /Users/username
/System/Library/CoreServices/ManagedClient.app/Contents/Resources/createmobileaccount -n $USERNAME -h /Users/$USERNAME
# Add newly created user to local admins group
dscl . -append /Groups/admin GroupMembership $USERNAME
# set login window to show username and password promts not a list of users
defaults write /Library/Preferences/com.apple.loginwindow SHOWFULLNAME 1
}
setADMPass ()
{
parsed1=${SITECODE:0:1}
parsed2=${SITECODE:1:1}
}
####################################### End define Functions ####################################################
############################################# Bgin Main Script #######################################################
userinput
setname
adbind
adcheck
adduser
echo $(dscl . -read /Groups/admin GroupMembership)
echo $(defaults 'read' /Library/Preferences/com.apple.loginwindow.plist SHOWFULLNAME)
# Reboot to apply changes
shutdown -r now "Rebooting to enable Mobile accounts"
Here's a funny way to do your encoding, abusing Bash's arithmetic:
string2code() {
# $1 is string to be converted
# return variable is string2code_ret
# $1 should consist of alphabetic ascii characters, otherwise return 1
# Each character is converted to its position in alphabet:
# a=01, b=02, ..., z=26
# case is ignored
local string=$1
[[ $string = +([[:ascii:]]) ]] || return 1
[[ $string = +([[:alpha:]]) ]] || return 1
string2code_ret=
while [[ $string ]]; do
printf -v string2code_ret '%s%02d' "$string2code_ret" "$((36#${string::1}-9))"
string=${string:1}
done
}
Try it:
$ string2code abc; echo "$string2code_ret"
010203
$ string2code ABC; echo "$string2code_ret"
010203
The magic happens here:
$((36#${string::1}-9))
The term 36# tells Bash that the following number is expressed in radix 36. In this case, Bash considers the characters 0, 1, ..., 9, a, b, c, ..., z (ignoring case). The term ${string:1} expands to the first character of string.
I found the answer thanks for all your help!
setADMPass ()
{
alower=abcdefghijklmnopqrstuvwxyz
site=$(echo $SITECODE | tr '[:upper:]' '[:lower:]')
parsed1=${site:0:1}
parsed2=${site:1:1}
tmp1=${alower%%$parsed1*} # Remove the search string and everything after it
ch1=$(( ${#tmp1} + 1 ))
tmp2=${alower%%$parsed2*} # Remove the search string and everything after it
ch2=$(( ${#tmp2} + 1 ))
if [[ $ch1 -lt 10 ]]; then
#statements
ch1=0$ch1
fi
if [[ $ch2 -lt 10 ]]; then
#statements
ch2=0$ch2
fi
passpre=$ch1$ch2
}
see if this helps! BASH 4+. If you find any issues, that'd be your homework.
#!/bin/bash
declare -A koba
i=1
for vi in {a..z};do koba=(["$vi"]="0${i}"); ((i++)); done
for vi in {A..Z};do koba=(["$vi"]="0${i}"); ((i++)); done
echo -en "\nEnter a word: "; read w; w="$( echo $w | sed "s/\(.\)/\1 /g" | cut -d' ' -f1,2)";
new_var="$(for ch in $w; do echo -n "${koba["${ch}"]}"; done)";
echo $new_var;

Changing SSH port with a bash script on CentOS

SO I wrote a script that can change the SSH port on CentOS but for some reason I'm encountering this error:
sshchangecOS6.sh: line 36: syntax error: unexpected end of file
This is the script:
#! /bin/bash
# This script changes the ssh port for logins on CentOS 5 and 6
if [[ $EUID -ne 0 ]]; then
echo "This script must be run as root"
exit 2
read -r -p "Would you like to change the ssh port? [Y/N] " response
if [[ $response =~ ^([yY][eE][sS]|[yY])$ ]]
then
read -p "What would you like to change the port to? (Chose between 1024-65535) " sshportconfig
if (( ("$sshportconfig" > 1024) && ("$sshportconfig" < 65535) )); then
echo "Port $sshportconfig" >> /etc/ssh/sshd_config
echo "--------------------------------------------------------------------"
echo ""
echo ""
echo "SSH port has been changed to: $sshportconfig. Written by Sincere the Minotaur."
echo ""
echo ""
echo "--------------------------------------------------------------------"
else
echo "Port chosen is incorrect."
exit 1
fi
else
sshPort=$(grep "Port" /etc/ssh/sshd_config) | head -n 1
echo "--------------------------------------------------------------------"
echo ""
echo ""
echo "SSH is still: $sshPort"
echo "Written by Sincere the Minotaur."
echo ""
echo "---------------------------------------------------------------------"
exit 1
fi
exit 0
Could someone explain where the errors are?
There is no fi for the first if if [[ $EUID -ne 0 ]]; then. You need to close every if with a fi.

Resources