1

I have a variable in my script that displays the user:

OWNER=$(grep 1000:1000: /etc/passwd|cut -f1 -d':')

Output will be something like:

joe

This is fine on a normal server where the os was installed & user was setup during the install. I run into problems on a vps where there is no initial user. I would like to add to the variable IF blank then the output should be "root" but I don't know where to start..

Thankyou

2 Answers 2

4

Something like this

[[ $OWNER == "" ]] && OWNER="root"

or

if [[ $OWNER == "" ]]; then
  OWNER="root"
fi
Sign up to request clarification or add additional context in comments.

3 Comments

Thankyou, Is there a way to have this check all contained in the variable? For example: OWNER=$(grep 1000:1000: /etc/passwd|cut -f1 -d':') [[ $OWNER == "" ]] && OWNER="root"
Yes : OWNER=$((grep 1000:1000: /etc/passwd || echo "root") | cut -f1 -d":")
@linuxnoob I like Imsteffan's suggestion. Alternatively you can just put a ; after the ) in your example.
1

Why not to check for return value of grep command? If it returns 1 when use root as user, otherwise - cut its result and use it.

LINE="`grep 1000:1000: /etc/passwd`"
[ $? -eq 0 ] && OWNER="`echo "$LINE"|cut -f1 -d":"`" || OWNER=root

3 Comments

You should quote both $USER and $LINE if you don't want weird expansion (e.g. $USER will always be echoed as having 1-space between word tokens and no leading or trailing spaces, regardless of however many it had from command output)
Thankyou, That worked perfectly.. Can the full expression be on one line or does it have to be on 2 lines?
@linuxnoob You can put ; to the end of each line and join them together one-by-one. BTW Do you really need it? It will be harder to understand such line. Instead you can create a function for that purpose. It is much better than combining all the lines into one.

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.