segunda-feira, 22 de dezembro de 2008

Correr scripts

$ chmod +x deltemp

The x marks the file as executable; if you list the permissions for the deltemp file afterward, you will see the x in position four, confirming this:

$ ls -l deltemp
-rwx------ 1 hermie other 55 Feb 19 14:02 deltemp

If you want other users to be able to run this script, give them both read and execute permission, like so:

$ chmod ugo+rx deltemp
$ ls -l deltemp
-rwxr-xr-x 1 hermie other 55 Feb 19 14:04 deltemp

Now the permissions show that any user can view or execute the deltemp script, but only you can modify it. To run the script, just enter its name at the command prompt, prefixed with ./ as shown here:

$ ./deltemp

Note: If the current directory is in the PATH environment variable, you can omit the ./ before the name.

But there's one important thing you should know about running shell scripts this way. When you enter the shell script name and tell Bash to run it, a subshell is created for the execution of the script. This subshell inherits all the shell environment variables, including the current directory, but you lose any changes made to that environment when the script terminates.

What's the practical meaning of this? Well, you might expect that the current directory would be /tmp after you've run the deltemp script, but it's not. You'll still be in hermie's home directory. And if we had set an environment variable inside the script, its value would be good only during the execution of the script. Here's an example to demonstrate this point. Create an executable setvar script with these lines:

PS1='My Prompt: '
echo $PS1

Now watch how the values of the current directory and the PS1 variable change:

$ PS1='Bash Me! '
$ echo $PS1
Bash Me! PS1 before setvar.
$ setvar
My Prompt: PS1 during setvar.
$ echo $PS1
Bash Me! PS1 after setvar.

It looks like this script is absolutely useless for the intended purpose of setting the environment variable. But a little trick will make it work the way you want. Run the script by prefixing the name with a dot and a space, like so:

. setvar

This tells Bash to run the setvar script in the current shell environment, instead of creating a temporary subshell. Verify for yourself that the command prompt does in fact change to My Prompt: after running this script.

http://lowfatlinux.com/linux-execute-script.html

1 comentário:

Anónimo disse...

Nice and thanks!

Acerca de mim