0

I wrote a shell script which automatically set up environment

#!/bin/sh

set path=(/dv/project/ $path)

I change the execution bit by

chmod +x init.sh

When I run it as

./init.sh

It prompted me with error

./init.sh: line 3: syntax error near unexpected token `('
./init.sh: line 3: `set path=(/dv/project/ $path)'

What could be the problem here? Thanks!

7
  • set path=? What kind of syntax is that? What is it supposed to do? Where did you see documentation that made you think it's valid? Commented May 17, 2016 at 13:54
  • @CharlesDuffy set is a valid command, as I know. It's used for setting up an environment options. Commented May 17, 2016 at 13:56
  • @denysdovhan, it's used for setting flags and modifying the list of command-line arguments. The OP is doing neither. set -- path=foo would be valid (setting $1 to "path=foo"), but that's not what was given. Commented May 17, 2016 at 13:57
  • BTW, #!/bin/sh means your shell is POSIX sh, which has no array support. Commented May 17, 2016 at 13:58
  • When I run this command directly from terminal, it works. When I put in a shell script, it just gave me error. Commented May 17, 2016 at 14:03

1 Answer 1

0

If using of set isn't required, just try this:

#!/bin/bash

path=(/dv/project/ $path)

As I have noticed, you're trying to extend your $PATH environment variable, right? There is a better way. Try this approach:

# Extend $PATH without duplicates
function _extend_path() {
  if ! $( echo "$PATH" | tr ":" "\n" | grep -qx "$1" ) ; then
    PATH="$1:$PATH"
  fi
}

# Add custom bin to $PATH
[ -d ~/.bin ] && _extend_path "$HOME/.bin"
Sign up to request clarification or add additional context in comments.

5 Comments

That's much less efficient than need be. _extend_path() { [[ $PATH =~ (^|:)"$1"(:|$) ]] || PATH+=":$1"; } -- one compound command, no subshells.
Also, path=( /dv/project/ $path ) is array syntax, which isn't valid with /bin/sh at all. Presumably you want #!/bin/bash?
Also, the function keyword isn't part of the POSIX sh standard, so that's a portability bug too; in POSIX sh, it's just extend_path() { with no function preceding to define a function. While I'm usually fond of bash extensions (when used with a #!/bin/bash shebang), this one adds no value over the portable alternative.
Yeah I'm trying to extend the variable. I'm running in a company server and I can't modify those scripts which would be executed when I connect to the server. The first method doesn't work either. It won't give me any error, but it doesn't have any effect. As for the second method, could you explain what I need to change?
@CharlesDuffy you're right. That makes sense.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.