In my Programm how can i Iterate trough ENV in bash
if [ ! -z $USER_1 ]
then
echo "$USER_1":$(openssl passwd -apr1 $PASS_1) > ./passwords
fi
if [ ! -z $USER_2 ]
then
echo "$USER_2":$(openssl passwd -apr1 $PASS_2) > ./passwords
fi
if [ ! -z $USER_3 ]
then
echo "$USER_3":$(openssl passwd -apr1 $PASS_3) > ./passwords
fi
if [ ! -z $USER_4 ]
then
echo "$USER_4":$(openssl passwd -apr1 $PASS_4) > ./passwords
fi
if [ ! -z $USER_5 ]
then
echo "$USER_5":$(openssl passwd -apr1 $PASS_5) > ./passwords
fi
And so on how can i do it with N "User" when i don't know N
EDIT April 14: my first version was incomplete, here is a fix.
Create a loop to loop through your users:
#!/bin/bash
USER_1=u1
USER_2=u2
N=5
for (( counter=1; counter<=N; counter++ ))
do
username=USER_${counter}
password=PASS_${counter}
echo "DEBUG: $username"
echo "DEBUG: ${!username}"
if [[ -n ${!username} ]]
then
#echo "$username:$(openssl passwd -apr1 "$password")"> ./passwords
echo "DEBUG: USER_${counter} inside if"
fi
echo "========="
done
To use on your setup, comment out the debug statements and uncomment your openssl line.
My first version did not properly user the variable counter inside the other USER_? variable.
With this particular script, USER_1 and USER_2 will trigger the if since USER_3 and more are not set.
Related
Maven doesn't have a great way to dynamically prompt for a UID / Password during a;
mvn deploy
command;
#Adligo
This can be accomplished using the following deploy.sh bash script;
#!/bin/bash
#Expand new lines \n
shopt -s xpg_echo
# Thanks https://medium.com/#Drew_Stokes/bash-argument-parsing-54f3b81a6a8f
while (( "$#" )); do
case "$1" in
-a | --artifactory_server) artServer="$2" ; shift 2 ;;
-b | --bearer_token) oauthToken="$2" ; shift 2 ;;
-d | --debug) debug=1 ; shift 1 ;;
-e | --oauth_server) oauthServer="$2" ; shift 2 ;;
-g | --group_path) groupPath="$2" ; shift 2 ;;
-l | --load_properties) loadProperties="y" ; shift 1 ;;
-m | --retry_seconds) retrySecs="$2" ; shift 2 ;;
-n | --gen-token-opts) genTokenOpts="$2" ; shift 2 ;;
-o | --oauth_uid) oauthUid="$2" ; shift 2 ;;
-p | --password) password="$2" ; shift 2 ;;
-r | --retrys) retrys="$2" ; shift 2 ;;
-s | --oauth_password) oauthPass="$2" ; shift 2 ;;
-t | --auth_type) authType="$2" ; shift 2 ;;
-u | --uid) uid="$2" ; shift 2 ;;
-v | --version) version="$2" ; shift 2 ;;
-*|--*=) # unsupported flags
echo "Error: Unsupported flag $1" >&2
exit 1
;;
*) # preserve positional arguments
PARAMS="$PARAMS $1"
shift
;;
esac
done
if [[ "y" == "$loadProperties" ]]; then
echo "loading defaults from deployProperties.sh "
. ./deployProperties.sh
fi
# Overwrite the cli options using the values in ./deployProperties.sh when not present
# Alphabetized
if [[ -z $artServer ]]; then
artServer=$ART_SERVER
fi
if [[ -z $authType ]]; then
authType=$AUTH_TYPE
fi
if [[ -z $debug ]]; then
debug=$DEBUG
fi
if [[ -z $oauthPass ]]; then
oauthPass=$OAUTH_PASS
fi
if [[ -z $oauthServer ]]; then
oauthServer=$OAUTH_SERVER
fi
if [[ -z $oauthToken ]]; then
oauthToken=$OAUTH_TOKEN
elif [[ "none" == $oauthToken ]]; then
oauthToken=""
fi
if [[ -z $oauthUid ]]; then
oauthUid=$OAUTH_UID
fi
if [[ -z $genTokenOpts ]]; then
genTokenOpts=$GENERATE_TOKEN_OPTS
fi
if [[ -z $groupPath ]]; then
groupPath=$GROUP_PATH
fi
if [[ -z $password ]]; then
password=$PASSWORD
fi
if [[ -z $retrys ]]; then
retrys=$RETRYS
fi
if [[ -z retrySecs ]]; then
retrySecs=$RETRY_SECS
fi
if [[ -z $version ]]; then
version=$VERSION
fi
if [[ -z $uid ]]; then
uid=$UID
fi
#Begin Logic
if [[ "$debug" = "1" ]]; then
echo "executing with parameters\n"
echo "artServer=$artServer"
echo "authType=$authType"
echo "debug=$debug"
echo "oauthPass=$oauthPass"
echo "oauthToken=$OoauthToken"
echo "oauthUid=$oauthUid"
echo "groupPath=$groupPath"
echo "password=$password"
echo "retrys=$retrys"
echo "retrySecs=$retrySecs"
echo "password=$password"
echo "uid=$uid"
echo "version=$version"
fi
if [[ -z $version ]]; then
echo No Version, exiting
exit 1
fi
function exec {
if [[ "$debug" = "1" ]]; then
echo "executing\n$1"
fi
status=$?
eval $1
status=$?
times=$(($retrys))
if [[ $times -lt 1 ]]; then
times=$((1))
fi
sleepTime=$(($retrySecs))
if [[ sleepTime -lt 1 ]]; then
sleepTime=$((10))
fi
count=$((1))
while [ $count -lt $times ]
do
echo "count is $count"
if [[ $status == 0 ]]; then
echo "command sucessful"
return 0
else
echo "Waiting $sleepTime seconds ..."
sleep $sleepTime
eval $1
status=$?
count=$(($count+1))
fi
done
}
jar=`ls target | grep jar`
echo Deploying the following to ART_SERVER is
echo $artServer
echo $jar
if [[ -f "pom.xml" ]]; then
echo "Found pom.xml file!"
else
echo "There is NO pom.xml file exiting;"
exit 0;
fi
if [[ "simple" = "$authType" ]]; then
if [[ -z $password ]]; then
read -s -p "Password: " password
fi
retrys=$(($retrys))
if [[ $retrys -le 1 ]]; then
echo "retrys are -le 1 running\ncurl -u $artUid:$password -X PUT \"$artServer/$groupPath/$version/$jar\" -T target/$jar"
curl -u $artUid:$password -X PUT "$artServer/$groupPath/$version/$jar" -T target/$jar
echo "retrys are -le 1 running\ncurl -u $artUid:$password -X PUT \"$artServer/$groupPath/$version/pom.xml\" -T pom.xml"
curl -u $artUid:$password -X PUT "$artServer/$groupPath/$version/pom.xml" -T pom.xml
else
exec "curl -u $artUid:$password -X PUT \"$artServer/$groupPath/$version/$jar\" -T target/$jar"
exec "curl -u $artUid:$password -X PUT \"$artServer/$groupPath/$version/pom.xml\" -T pom.xml"
fi
# note md5 checksums are hidden by default
# https://jfrog.com/knowledge-base/how-to-show-the-checksum-files-when-browsing-artifacts-from-the-direct-url/
elif [[ "oauth" = "$authType" ]]; then
if [[ -z $oauthUid ]]; then
read -p "OAuth User Id: " oauthUid
fi
if [[ -z $oauthToken ]]; then
if [[ -z $oauthPass ]]; then
read -s -p "OAuth Password: " oauthPass
fi
status=$?
cmd="curl -XPOST $oauthServer $generateTokenOpts --data-urlencode \"username=$oauthUid\" --data-urlencode \"password=$oauthPass\""
status=$?
if [[ "0" == "$status" ]]; then
echo "Unable to contatct the following server, is it down?"
echo "$oauthServer"
exit 0;
fi
oauthResponce=`eval $cmd`
if [[ "$DEBUG" = "1" ]]; then
echo "\n\oauthResponce\n$oauthResponce"
echo "\n\n\n parsing token"
fi
oauthToken=`echo $oauthResponce | sed "s/{.*\"access_token\":\"\([^\"]*\).*}/\1/g"`
echo "\n\n\nGot the following token;"
echo $oauthToken
else
echo "Using provided oauthToken"
fi
retrys=$(($retrys))
if [[ $retrys -le 1 ]]; then
echo "retrys are -le 1 running\ncurl -u $oauthUid:$oauthToken -X PUT \"$artServer/$groupPath/$version/$jar\" -T target/$jar"
curl -u $oauthUid:$oauthToken -X PUT "$artServer/$groupPath/$version/$jar" -T target/$jar
echo "retrys are -le 1 running\ncurl -u $oauthUid:$oauthToken -X PUT \"$artServer/$groupPath/$version/pom.xml\" -T pom.xml"
curl -u $oauthUid:$oauthToken -X PUT "$artServer/$groupPath/$version/pom.xml" -T pom.xml
else
exec "curl -u $oauthUid:$oauthToken -X PUT \"$artServer/$groupPath/$version/$jar\" -T target/$jar"
exec "curl -u $oauthUid:$oauthToken -X PUT \"$artServer/$groupPath/$version/pom.xml\" -T pom.xml"
fi
else
echo "Unknown AUTH_TYPE must be one of (simple, oauth)"
fi
And a deployProperties.sh file like;
# ART short for Artifactory
ART_SERVER=http://localhost:8081/artifactory/libs-snapshot-local
#
# Try to keep this out of this file and use it from the
# CLI dialog which is a bit more secure :)
#
ART_PASSWORD=
#
# This is the uid of the ART_SERVER
#
ART_UID=admin
#
# This is either simple or oauth (for OAuth bearer tokens)
#
AUTH_TYPE=simple
# 0 is off 1 is on
DEBUG=0
GENERATE_TOKEN_OPTS=`echo -d "instance=maven"`
GROUP_PATH=
RETRYS=3
RETRY_SECS=10
#
# It is NOT recommend to use this setting, as it is less secure
# than the OAUTH_TOKEN setting
#
OAUTH_PASS=
#
# This token MAY be created by this script and copied into this file
# NOTE there is NO option for a OAUTH_PASSWORD which is an intentional security feature
# use the CLI to dialog for the OAuth password
#
OAUTH_TOKEN=
OAUTH_SERVER=
#
# The User Identifier of the OAuth requests
#
OAUTH_UID=
VERSION=
export ART_SERVER ART_PASSWORD ART_UID AUTH_TYPE GENERATE_TOKEN_OPTS RETRYS RETRY_SECS OAUTH_PASS OAUTH_TOKEN OAUTH_SERVER OAUTH_UID TOKEN VERSION
This is now hosted here;
https://github.com/adligo/artifactory_deploy.sh.adligo.org
Please contribute and allow shorter answers to be posted to stack overflow :)
I write the following shell script and cannot understand how it works.
#!/bin/bash
[ -n $HOME ]
echo $?
[ -z $HOME]
echo $?
Output = 0
1
What is the use of -n and -z options
With -n and -z you can check the length of a variable.
if [ -n "$HOME" ]; then
echo "length of \$HOME ist not zero"
fi
if [ -z "$HOME" ]; then
echo "length of \$HOME is zero"
fi
I have many javascript files in my solaris server which have some debug, print and trace statements which I want to comment. There are hundreds of file like this.
I have found a script to do this but the problem is the script is removing the urhk_b2k_printRepos statement instead of commenting it. The script is as below:
if [ $# -ne 2 ]
then
echo "usage: prdel <script file name> <directory in which scripts are present>"
exit 1
fi
file=$1
dir=$2
if [ ! -s ${file} ]
then
echo "script file ${file} either does not exist or is empty (zero bytes)"
echo "Exiting..."
exit 1
fi
if [ ! -d ${dir} ]
then
echo "Invalid directory ${dir} entered"
echo "Exiting..."
exit 1
fi
cordir="./corrected"
prlogdir="./prlog"
if [ -d ${cordir} ]
then
echo "The corrected directory exist in the path, Please remove and run the tool again"
echo "Exiting..."
exit 1
else
mkdir ${cordir}
fi
if [ -d ${prlogdir} ]
then
echo "The prlog directory exist in the path, Please remove and run the tool again"
echo "Exiting..."
exit 1
else
mkdir ${prlogdir}
fi
errFile="$prlogdir/scr_err.rpt"
sucFile="$prlogdir/scr_suc.rpt"
Lines=`wc -l $file`
cntr=1
while [ $cntr -le $Lines ]
do
src=`head -$cntr $file|tail -1`
echo "$cntr. Processing $src...."
srcPath="${dir}/${src}"
if [ ! -s ${srcPath} ]
then
echo "Script file ${src} does not exist in the path given" >> ${errFile}
else
cp $srcPath $cordir/$src.tmp
srctemp="$cordir/$src.tmp"
srccor="$cordir/$src.corrected"
printcnt=`grep -ci "^[ ]*print" $srctemp`
if [ $printcnt -ne 0 ]
then
cat $srctemp|sed 's/^[ ]*[ ]*print[ ]*(/#print(/'|sed 's/^[ ]*[ ]*PRINT[ ]*(/#PRINT(/' > $srccor
mv $srccor $srctemp
fi
prreposcnt=`grep -ci "printrepos" $srctemp`
if [ $prreposcnt -ne 0 ]
then
cat $srctemp|sed 's/^.*urhk_b2k_printRepos.*/#Printrepos statement removed/'|sed 's/^.*urhk_B2k_PrintRepos.*/#Printrepos statement removed/'|sed 's/^.*urhk_B2k_printRepos.*/#Printrepos statement removed/'|sed 's/^.*urhk_b2k_PrintRepos.*/#Printrepos statement removed/' > $srccor
else
cp $srctemp $srccor
fi
echo "Script file $src correction is done" >> ${sucFile}
rm $srctemp
diff $srcPath $srccor >> $prlogdir/$src.diff.rpt
fi
cntr=`expr $cntr + 1`
done
echo "done"
I am completely new to shell scripting. Can anyone help me to modify this script to comment "urhk_b2k_printRepos" lines and also comment "TRACE ON" lines.
I have a bash script that asks the user for their details.
I'm setting a limit to how long we wait for the input. I've found this and it appears to what I want.
timelimit=5
echo -e " You have $timelimit seconds\n Enter your name quickly: \c"
name=""
read -t $timelimit name
#read -t $timelimit name <&1
# for bash versions bellow 3.x
if [ ! -z "$name" ]
then
echo -e "\n Your name is $name"
else
echo -e "\n TIME OUT\n You failed to enter your name"
fi
It shows "You have 5 seconds..." any way to update the output so it shows 4,3,2,1 etc as it counts down ?
Thanks
I have tried most of these answers and none of them worked perfectly for me.
Been playing with this for a local developer deployment script.
This solves a few of the issues noted, like including printed output, etc.
Also wrapped as a function for portability. I'm keen to see any improvements.
Here is my solution:
#!/bin/bash
# set -euo pipefail
READTIMEOUT=5
function read_yn {
MESSAGE=$1
TIMEOUTREPLY=$2
NORMALREPLY="Y"
if [ -z "${TIMEOUTREPLY}" ]; then
TIMEOUTREPLY="Y"
fi
TIMEOUTREPLY_UC=$( echo $TIMEOUTREPLY | awk '{print toupper($0)}' )
TIMEOUTREPLY_LC=$( echo $TIMEOUTREPLY | awk '{print tolower($0)}' )
if [ "${TIMEOUTREPLY_UC}" == "Y" ]; then
NORMALREPLY="N"
fi
NORMALREPLY_UC=$( echo $NORMALREPLY | awk '{print toupper($0)}' )
NORMALREPLY_LC=$( echo $NORMALREPLY | awk '{print tolower($0)}' )
for (( i=$READTIMEOUT; i>=0; i--)); do
printf "\r${MESSAGE} [${NORMALREPLY_UC}${NORMALREPLY_LC}/${TIMEOUTREPLY_UC}${TIMEOUTREPLY_LC}] ('${TIMEOUTREPLY_UC}' in ${i}s) "
read -s -n 1 -t 1 waitreadyn
if [ $? -eq 0 ]
then
break
fi
done
yn=""
if [ -z $waitreadyn ]; then
echo -e "\nNo input entered: Defaulting to '${TIMEOUTREPLY_UC}'"
yn="${TIMEOUTREPLY_UC}"
else
echo -e "\n${waitreadyn}"
yn="${waitreadyn}"
fi
}
read_yn "TESTING" "y"
GIST: https://gist.github.com/djravine/7a66478c37974940e8c39764d59d35fa
LIVE DEMO: https://repl.it/#DJRavine/read-input-with-visible-countdownsh
This should work and shouldn't overwrite input, bit more long winded than the other solutions.
#!/bin/bash
abend()
{
stty sane
exit
#Resets stty and then exits script
}
DoAction(){
stty -echo
#Turn off echo
tput sc
#Save cursor position
echo -ne "\033[0K\r"
# Remove previous line
tput cuu1
#Go to previous line
tput el
#clear to end of line
echo "You have $(($time-$count)) seconds"
#Echo timer
echo -n "$Keys"
#Echo currently typed text
stty echo
#turn echo on
tput rc
#return cursor
}
main()
{
trap abend SIGINT # Trap ctrl-c to return terminal to normal
stty -icanon time 0 min 0 -echo
#turn of echo and set read time to nothing
keypress=''
time=5
echo "You have $time seconds"
while Keys=$Keys$keypress; do
sleep 0.05
read keypress && break
((clock = clock + 1 ))
if [[ clock -eq 20 ]];then
((count++))
clock=0
DoAction $Keys
fi
[[ $count -eq $time ]] && echo "you have run out of time" && abend
done
stty sane
echo Your username was $Keys
echo "Thanks for using this script."
exit 0
}
main
This seems to work:
$ cat test.sh
total=5 # total wait time in seconds
count=0 # counter
while [ ${count} -lt ${total} ] ; do
tlimit=$(( $total - $count ))
echo -e "\rYou have ${tlimit} seconds to enter your name: \c"
read -t 1 name
test ! -z "$name" && { break ; }
count=$((count+1))
done
if [ ! -z "$name" ] ; then
echo -e "\nyour name is $name"
else
echo -e "\ntime out"
fi
#!/bin/bash
timelimit=6
name=""
for (( i = 1 ; i <= $timelimit; i++ )); do
echo -ne "\rYou have $(expr $timelimit - $i) seconds. Enter your name quickly: \c"
[ ! -z "$name" ] && { break ; }
read -t 1 name
done
if [ -z "$name" ]; then
echo -e "\n TIME OUT\n You failed to enter your name"
else
echo -e "\n Your name is $name"
fi
this should work
This works fine and fast for me:
#!/bin/bash
#Sets starttimestamp
starttime=$(date +%s)
#Sets timeout
timeout=5
#sets successflag default to false
success=false
#Save Cursorposition
echo -n -e "\033[s"
#While time not up
while [ $(($starttime+$timeout)) -gt $(date +%s) ] ; do
#Return to saved Cursorpositon
echo -n -e "\033[u"
#Display time left
echo "$(((starttime+timeout)-$(date +%s))) seconds left"
#Ask for 1 char then go on in loop make it look like an ongoing input by adding the user variable to the prompt
if read -p foo="Username: $user" -n 1 -t 1 c ; then
#If user hits return in time c will be empty then break out of loop and set success true
if [[ $c == "" ]] ; then
success=true
break
fi
# Append latest character to user variable
user=${user}${c}
unset c
fi
done
if $success ; then
echo "Yiha!"
else
echo "Too late!"
fi
This question already has answers here:
Test for non-zero length string in Bash: [ -n "$var" ] or [ "$var" ]
(7 answers)
Closed 8 years ago.
I don't set any values for $pass_tc11; so it is returning null while echoing. How to compare it in if clause?
Here is my code. I don't want "Hi" to be printed...
-bash-3.00$ echo $pass_tc11
-bash-3.00$ if [ "pass_tc11" != "" ]; then
> echo "hi"
> fi
hi
-bash-3.00$
First of all, note you are not using the variable correctly:
if [ "pass_tc11" != "" ]; then
# ^
# missing $
Anyway, to check if a variable is empty or not you can use -z --> the string is empty:
if [ ! -z "$pass_tc11" ]; then
echo "hi, I am not empty"
fi
or -n --> the length is non-zero:
if [ -n "$pass_tc11" ]; then
echo "hi, I am not empty"
fi
From man test:
-z STRING
the length of STRING is zero
-n STRING
the length of STRING is nonzero
Samples:
$ [ ! -z "$var" ] && echo "yes"
$
$ var=""
$ [ ! -z "$var" ] && echo "yes"
$
$ var="a"
$ [ ! -z "$var" ] && echo "yes"
yes
$ var="a"
$ [ -n "$var" ] && echo "yes"
yes
fedorqui has a working solution but there is another way to do the same thing.
Chock if a variable is set
#!/bin/bash
amIEmpty='Hello'
# This will be true if the variable has a value
if [ $amIEmpty ]; then
echo 'No, I am not!';
fi
Or to verify that a variable is empty
#!/bin/bash
amIEmpty=''
# This will be true if the variable is empty
if [ ! $amIEmpty ]; then
echo 'Yes I am!';
fi
tldp.org has good documentation about if in bash:
http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_07_01.html