How to convert "$#" from bash to Powershell? - bash

I have to change a bash script into a PowerShell script, but I dont really get the condition in the if-statement.
if [ $# -eq 0 ]
then
name='plmapp-all'
else
name="$1"
Does somebody know what's $# and how this statement would look like in PowerShell?

$# is an internal bash variable that holds the number of arguments passed to a script. Its PowerShell equivalent is $args.Count. $args is an automatic variable holding a list with the arguments passed to the script (like $# in bash). Since PowerShell is working with objects you can obtain the argument count directly from the $args array without the need for an additional variable.
The whole expression would look like this in PowerShell:
if ($args.Count -gt 0) {
$name = 'plmapp-all'
} else {
$name = $args[0]
}
You could simplify that to
if ($args) {
$name = 'plmapp-all'
} else {
$name = $args[0]
}
because PowerShell interprets non-empty arrays as $true and empty arrays as $false in a boolean context.
An even more streamlined alternative would be:
$name = #($args + 'plmapp-all')[0]
Since $args is always an array the + operator appends the string to that array, then the index operator selects the first element from the result array.
[] + 'plmapp-all' → [ 'plmapp-all' ]
[ 'something' ] + 'plmapp-all' → [ 'something', 'plmapp-all' ]

Related

passing parameters and return values in shell

I have written a function named 'connectTo' which takes paramaters named 'options' and it should return some string by echoing before return.
connectTo ${options}
this works i.e arguments get passed in this but when i write
str=$(connectTo ${options})
then connectTo is working as if no arguments were passed>
I am new to shell scripting and obviously doing something wrong but what?
(remember i need a string to be returned from fuction which cannot be a global variable)
function connectTo(){
local flag=false
local str=""
for i in $#; do
if [ "$flag" = true ]; then
str=$i
flag=false
elif [[ "$i" = "--foo" || "$i" = "-f" ]]; then
flag=true
fi
echo "$i"
done;
if [ "$str" = "" ]; then
echo ""
return 0
fi
echo "found"
return 0
}
In case of connectTo ${options} the arguments get printed while in second case they don't
you should not use '$' sign while assigning a variable. so it should be
str =connectTo [value_of_argument]
$ is used to access the value of variable.

Using two expressions in one bash "IF" statement

I have a script that I am making, it is a very simple login script.
I was wondering if you could have two expressions in one bash "IF" statement, like so:
if [ $User == "root" and $Pass == "passwd" ]
If anyone could answer, that would be great :D
In bash, you should use the conditional expression
if [[ $User == root && $Pass == passed ]];
If you need to or want to use test, then join two test commands with &&:
if [ "$User" = root ] && [ "$Pass" = passed ];
Be sure to quote any parameter expansions that are used as arguments to [, and use = instead of ==.
Use -a for and. And, = instead of ==. Also you'd better double quote variables, otherwise you'll see a syntax error when the variables are not set.
if [ "$User" = "root" -a "$Pass" = "passwd" ]

How to call and pass arguments to functions with spaces in unix

I'm creating a unix script that will call and pass arguments to function in unix. Once called, the function should identify how many parameters passed to it. I tried the normal way of calling and passing of arguments to function and it works. However, I noticed that the function is counting the arguments word by word and my problem on it is that, what if I have a single argument that contains spaces or a multiple arguments but some of it should be single argument but with spaces? Is it possible to identify by the function that the arguments specified should be considered as single argument? I already used double quotation and it didn't work.
Here is the relevant portion of my script.
#!/usr/bin/ksh
ARG_CNT() {
SCRIPT_AR_CNT=$#
if [ SCRIPT_AR_CNT -lt 3 ]; then
echo "Error. Incorrect number of arguments specified."
echo "Error. Execute \"./script_template.ksh -h\" for help."
exit 1
fi
}
echo "Specify the Arguments: "
read SCRIPT_AR
if [ "${SCRIPT_AR}" = "" ] || [ "${SCRIPT_AR}" = "." ]; then
exit
else
ARG_CNT $SCRIPT_AR
fi
Your problem is that you're not quoting your variables:
ARG_CNT $SCRIPT_AR
If you don't quote regular variables, they'll be split on $IFS. You should only leave out quotes if you explicitly want this kind of splitting, and that should be rare (so comment it). Quoting also slightly improves performance.
ARG_CNT "$SCRIPT_AR"
If I may suggest more edits:
#!/usr/bin/ksh
arg_cnt() {
#ALL_CAPS should be reserved to env variables (exported vars) and shell config variables
script_ar_cnt=$#
[ script_ar_cnt -lt 3 ] && {
echo "Error. Incorrect number of arguments specified."
echo "Error. Execute \"./script_template.ksh -h\" for help."
exit 1
} >&2
}
echo "Specify the Arguments: "
read script_ar
ex_dataerr=65 # data format error
{ [ -z "$script_ar" ] || [ "$script_ar" = "." ]; } && exit "$ex_dataerr"
arg_cnt "$script_ar"

Conditional check in a shell

I have a python script p.py which does exit("ABC") for some files. I would like to write a Ubuntu shell to copy the files which make the script exit("ABC") into a folder:
#!/bin/bash
FILES=*.txt
TOOL=p.py
TAREGT=../TARGET/
for f in $FILES
do
if [ $(python $TOOL $f) = "ABC" ]
then
echo "$f"
cp $f $TARGET
fi
done
but the condition check if [ $(python $TOOL $f) = "ABC" ] does not seem to work, it says ./filter.sh: line 13: [: =: unary operator expected. Could anyone tell me what is wrong?
The parameter to exit() is what the Python script returns (success / error). (Documentation of Python's exit(). Note how exit( "ABC" ) doesn't return "ABC", but prints that to stderr and returns 1.)
The return code is what ends up in the $? variable of the calling shell, or what you would test for like this:
# Successful if return code zero, failure otherwise.
# (This is somewhat bass-ackwards when compared to C/C++/Java "if".)
if python $TOOL $f
then
...
fi
The $(...) construct is replaced with the output of the called script / executable, which is a different thing altogether.
And if you're comparing strings, you have to quote them
if [ "$(python $TOOL $f)" = "ABC" ]
or use bash's improved test [[:
if [[ $(python $TOOL $f) = "ABC" ]]

Unix shell functions, command substitution and exit

Please explain me about how to use unix shell function correctly.
For example we have following functions f and g:
f()
{
#do something
return $code
}
g()
{
print $something
}
We can use function f in the next way:
f
if [[ $? -eq 0 ]]; then
#do 1
else
#do 2
fi
This function performs some work and exits with some exit status.
And we can analyze this exit status.
We can use function g in the next way:
g
or
result=$(g)
if [[ $result = "something" ]]; then
#do something
fi
In first case we just called function.
In the second case we used command substitution to assign all text that function prints to stdout to variable result.
But what if there is following function:
z()
{
user=$1
type=$2
if [[ $type = "customer" ]]; then
result=$(/somedir/someapp -u $user)
if [[ $result = "" ]]; then
#something goes wrong
#I do not want to continue
#I want to stop whole script
exit 1
else
print $result
fi
else
print "worker"
fi
}
I can use function z in the next way:
z
If something goes wrong then whole script will be stopped.
But what if somebody uses this function in command substitution:
result=$(z)
In this case if someapp returns empty string script will not be stopped.
Is it not correct approach to use exit in functions?
I don't have a way to test this right now, but ksh (maybe bash too), can scope variables inside functions.
z()
{
typeset result
user=$1
type=$2
if [[ $type = "customer" ]]; then
result=$(/somedir/someapp -u $user)
if [[ $result = "" ]]; then
#something goes wrong
#I do not want to continue
#I want to stop whole script
exit 1
else
print $result
fi
else
print "worker"
fi
}
Notice the insertion of typeset result near the top.
You may need to use the alternate declartion of function for this feature to work, i.e.
function z {
#....
}
I hope this helps.
You could also do something like
result=$(z ; "eval retCode=\$? ; echo \$retCode" )

Resources