Unix script - String Validation - shell

I'm very new to Unix scripting (.ksh). I have to implement a functionality to check whether my argument says "welcome" present in an string array e.g.
{"welcome","test","exit"}
The logic is similar to String.contains in Java.
Any help will be appreciated.

You can do something like this. Following is in bash, you need to change it accordingly to ksh.
script
array=(welcome test exit)
string='welcome';
for item in ${array[*]}
do
if [[ $string =~ .*$item.* ]]
then
echo "It's present!"
fi
done
Output
It's present!
To iterate over arguments passed to a shell script, use for with empty in, that default the iteration over arguments, or in '$#'.

Related

How can you use the actual regex value in an environment variable?

I'm writing a shell script for an assignment. The script is supposed to read regex argument and then use that regex. The problem is, if the user doesn't use single/double quotations then the regex will be evaluated before I need it to be evaluated.
Here's an example; let's say that the user executed the script and passed *f* as an argument, and the code has the following lines:
arg=$1 #*f*
echo "$arg"
In the above example echo returns a file name in the current directory that contains the regex *f*. I need echo to print *f*. It works if the user passes '*f*', but is there no other way?

While loop in .sh file with condition to compare if a string contains a substring

I have a .sh file in which I have written the following function. The command that calls this function will have the arguments- file1.war, file2.war ... fileN.war and other arguments.
I want to do a certain operation to the .war files and something else for the arguments after it. So I have written a while loop that will run till the arguments are .war files, and when an argument is encountered without .war extention, it will exit the loop and run the code below it for the rest of the arguments.
Here is the function in .sh file :
copyWarFiles()
{
downloadFileName=$1
shift 1
extn=".war"
while [ condition ]
do
log "war file $downloadFileName .."
#some operation..
downloadFileName=$1
shift 1
done
#operations for the rest of the arguments...
}
What should I give as condition that will return true if $downloadFileName ends with .war? I tried giving
$downloadFileName==*".war" (following the accepted answer in this )
and I also tried this :
`test "${downloadFileName#*$extn}" != "$downloadFileName"`
(following the accepted answer here) where extn is another variable I declared and assigned to .war.
But in both the cases, I see that it never enters the while loop. I think I have gone wrong with the syntax or something. Thank you for your help in advance.
What should I give as condition that will return true if $downloadFileName ends with ".war"? I tried giving $downloadFileName==*".war" […]
Bash, unlike typical programming languages, doesn't recognize == as a special operator; it's just yet another argument to the [ command. So you need to set it off with spaces.
Also, the [ command doesn't support having a pattern on the right-hand-side of ==; you need to use the special [[ ... ]] notation.
So:
while [[ $downloadFileName == *".war" ]]
Note, though, that the double-quotes around .war don't actually have any effect: none of the characters in .war are special characters that need to be quoted. Conversely, it's a best practice to always put variable expansions in double-quotes, in case the variables contain special characters. ([[ actually negates most of the problematic behaviors, but it's just a good habit to be in.)
So:
while [[ "$downloadFileName" == *.war ]]
Why not just:
check=`echo $downloadFile | grep '\.war'`
if [ -n "$check" ]; then
echo $downloadFile ends in .war
fi

Error: =: command not found (Bash Script)

I found a nifty little shell script that I wanted to use from this website here. I have followed everything step-by-step, but receive the following error when running this on my CentOS box.
./deploy: line 3: =: command not found
Line 3 only contains...
$ERRORSTRING = "Error. Please make sure you've indicated correct parameters"
I've tried toying around with a bit, but don't understand why it won't accept the "=" character. Is there something wrong with the script, or is it merely something different in the way that my server processes the script?
Thanks!
Gah, that script is full of bad scripting practices (in addition to the outright error you're running into). Here's the outright error:
$ERRORSTRING = "Error. Please make sure you've indicated correct parameters"
As devnull pointed out, this should be:
ERRORSTRING="Error. Please make sure you've indicated correct parameters"
A couple of lines down (and again near the end), we have:
echo $ERRORSTRING;
...which works, but contains two bad ideas: a variable reference without double-quotes around it (which will sometimes be parsed in unexpected ways), and a semicolon at the end of the line (which is a sign that someone is trying to write C or Java or something in a shell script). Use this instead:
echo "$ERRORSTRING"
The next line is:
elif [ $1 == "live" ]
...which might work, depending on whether the value of $1 has spaces, or is defined-but-blank, or anything like that (again, use double-quotes to prevent misparsing!). Also, the == comparison operator is nonstandard -- it'll work, because bash supports it in its [ ... ] builtin syntax, but if you're counting on having bash extensions available, why not use the much cleaner [[ ... ]] replacement? Any of these would be a better replacement for that line:
elif [ "$1" = "live" ]
elif [[ $1 == "live" ]]
elif [[ "$1" == "live" ]]
Personally, I prefer the last. The double-quotes aren't needed in this particular case, but IMO it's safest to just double-quote all variable references unless there's a specific reason not to. A bit further down, there's a elif [ $2 == "go" ] that the same comments apply to.
BTW, there's a good sanity-checking tool for shell scripts at www.shellcheck.net. It's not quite as picky as I am (e.g. it doesn't flag semicolons at the ends of lines), but it pointed out all of the actual errors in this script...
"Devnulls" answer was correct -- I had to remove the spaces around the "=" and remove the "$" from that line as well. The end result was...
ERRORSTRING="Error. Please make sure you've indicated correct parameters"
I've upvoted Devnull and gniourf_gniourf's comments.
Thank you to all whom have assisted!

Read input, save it to a dynamically-named variable and check if given input was empty

Consider a generic ask() function that asks the user a question, reads the input and saves it in a variable named according to one of the function's arguments.
ask() {
local question="$1"
local varname="$2"
echo "$question"
read $varname
}
Suppose I want to ask the user what is his favourite pet and store the answer in a variable named $pet. Usage would be as follows:
ask "What is your favourite pet?" pet
What I want to do and need help with is check if the user's input was empty, and in that case set the user's input to some string. I would be able to do this easily if the name of the variable the user's input is stored in was constant, like so:
if [ -z "$pet" ]; then
pet="foo"
fi
However the name of the variable I want to check whether or not is empty is whatever I pass in as the second argument. How can I check if the variable (named as per the value of $varname) containing the user's input is empty? The solution should be as portable and standard as possible, and must work under bash and zsh specifically.
In bash, ${!varname} gives you the value of the variable whose name is the value of $varname, but as far as I know, this syntax is not supported by zsh. If you want something that works in both bash and zsh, you may have to use the oldfashioned eval value=\${$varname} and then check $value. You should only use this if you know in advance that the value of $varname is a legal variable name; otherwise this is unsafe.
maybe:
ask() {
name=$1;shift
read -r -p "$# >" var
eval "$name='$var'"
}
ask pet "What is your favourite pet?"
pet=${pet:-foo}
echo "PET: $pet"
Based on the input thus far I managed to get a satisfying solution.
eval varname_tmp=\$$varname
if [ -z "$varname_tmp" ]; then
eval "$varname=foo"
fi

Trouble getting shell script to work with simple conditional statement

This is part of a bigger project but I can't get this part to work and I'm having a brain fart.
#!/bin/bash
echo -n "Do you wish to download/checkout the source code? > "
read text
if ["$text" = "Yes"]
then
do something
else
do something else
fi
It should simply be reading in what the user types and then go through a simple conditional. but I get this error
./check.sh: line 6: [Yes: command not found
I thought I had formatted the shell script correctly but I guess not.
Add spaces after brackets:
if [[ "$text" = "Yes" ]]
When performing operations on strings it's always a good idea to use double square brackets. It will make your code work properly with spaces and new lines.

Resources