0

I have some bash code that i am running in a zsh shell on macos.

Code seems to work fine when i run in the shell, but when i run the file from my path, it only brings back the initial and not the initial+surname, any help most appreciated.

user="Steve Thomas"
dbuser=$user
initial="${user%"${user#?}"}"
userie=( $( echo $dbuser | cut -d' ' -f1- ) )
userlastname=${userie[2]}
fulluser="${initial}${userlastname}"
echo $fulluser

when run in shell i get what is expected

SThomas

and when i run as file.sh from path i get..

S

Not sure what i am doing wrong here, please advise.

2
  • Your question is confusing. When you are running it as plain file.sh, the #! line determines, which shell is used, but there is no such line in your script. Also you tag the question as bash and zsh, and we don't know what shell is processing your code. Please make up your mind first what programming language (= shell) you are using, and then write the program in it. Commented Oct 20, 2022 at 9:25
  • bash code that i am running in a zsh shell : bash code should be run by a bash shell, similar to Java code should be compiled by a Java-compiler (compiling in by COBOL wouldn't do any good). Commented Oct 24, 2022 at 11:10

1 Answer 1

1

In bash, arrays are indexed from 0, not 1 like in zsh. So, to make the script work in bash, change line 5 to

userlastname=${userie[1]}

You can even make it universal for both the shells:

startindex=2
if [[ $BASH_VERSION ]] ; then
   startindex=1
fi
...
userlastname=${userie[startindex]}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the reply, works perfectly now for me also. I am new to BASH and zsh, something for me to keep an eye on going forward. :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.