yazz.com
yazz.com

Reputation: 58806

In Linux shell do all commands that work in a shell script also work at the command prompt?

I'm trying to interactively test code before I put it into a script and was wondering if there are any things that behave differently in a script?

Upvotes: 1

Views: 205

Answers (3)

Shawn Chin
Shawn Chin

Reputation: 86934

As David rightly pointed out, watch out for environment variables.

Depending on how you intend to launch your script, variables set in .profile and .bashrc may not be available. This is subject to whether the script is launched in interactive mode and whether it was a login shell. See Quick Startup File Reference.

A common problem I see is scripts that work when run from the shell but fail when run from another application (cron, nagios, buildbot, etc.) because $PATH was not set.

To test if a command/script would work in a clean session, you can login using:

ssh -t localhost "/bin/bash --noprofile --norc"

This ensures that we don't inherit any exported variables from the parent shell, and nothing from .profile or .rc.

If it works in a clean session and none of you're commands expect to be in interactive mode, then you're good to go!

Upvotes: 2

David
David

Reputation: 2803

When you execute a script it has its own environment variables which are inherited from the parent process (the shell from which you executed the command). Only exported variables will be visible to the child script.

More information:

By the way, if you want your script to run in the same environment as the shell it is executed in, you can do it with the point command:

. script.sh

This will avoid creating a new process for you shell script.

Upvotes: 3

qbert220
qbert220

Reputation: 11556

A script runs in exactly the same way as if you typed the content in at a shell prompt. Even loops and if statements can be typed in at the shell prompt. The shell will keep asking for more until it has a complete statement to execute.

Upvotes: 2

Related Questions