2

I have come across a script that is supposed to make adding a user to a linux system easier. I am fairly new to bash scripts so i am trying to figure out what each line of said script is doing. Now i am trying to find out what this part of the script means "^$username" what is the function of the ^ before the variable?

for some more context here is the part of the script this variable is in:

if [ $(id -u) -eq 0 ]; then read -p "Enter username : " username read -s -p "Enter password : " password egrep "^$username" /etc/passwd >/dev/null 
1
  • Reading the section on regular expressions in the grep manual will enlight you. Commented Nov 24, 2016 at 10:32

2 Answers 2

4

It's a literal ^. In this case, it's being passed to egrep, which takes extended regular expressions, a kind of way of specifying a pattern to match in a given string (kind of like globbing/wildcards, but much more powerful). ^ just means "This has to be at the start of the string/line". So in this case, it'll match every line in /etc/passwd that starts with the contents of the "username" variable.

(Note there's a potential bug here, because if there's a user rich and a user richard, typing the username rich will also match richard.)

2
  • Thanks @Muzer the following has removed the potential bug: if [ $? -eq 0 ]; then echo "$username exists!" exit 1 Commented Nov 24, 2016 at 10:39
  • @a.smith, if you only added checking of error code of grep, then it didn't solve a bug Muzer was talking about. You won't be able to add user 'rich', when you have a user 'richard'. Regexp is too wide here. Think about using "^$username:" - colon is used to separate fields in /etc/passwd, so it would match whole field as a username. Commented Nov 24, 2016 at 12:00
1

It's part of a regular expression and just means "at beginning of line".

For a nice list on regular expressions, take a look at grymoire.

0

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.