This is a piece of code found on Internet
#include <stdio.h>
#include <string.h>
int main(int argc, char* argv[])
{
putenv("PATH=/nothinghere");
//setenv("PATH","/nothinghere");
system(argv[1]);
return 0;
}
if I do
$./a.out "ls"
sh: 1: ls: not found
Of course But what if
$./a.out "echo $PATH"
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games
It print the original $PATH
!!
If we create a new shell then do the samethings
int main(int argc, char* argv[])
{
putenv("PATH=/nothinghere");
//setenv("PATH","/nothinghere");
system("/bin/sh");
return 0;
}
$./a.out
$ echo $PATH
/nothinghere
$ ls
/bin/sh: 2: ls: not found
Why?
Is it kind of problem about fork
or the implementation of echo
?
echo $PATH doesn't create a variable, it prints the current contents of an already-existing variable.
$PATH is a environment variable that is file location-related. When one types a command to run, the system looks for it in the directories specified by PATH in the order specified. You can view the directories specified by typing echo $PATH in the terminal.
If you want to have just the String, remove $PATH + the semicolon (:) from your command. It doesn't matter if you use echo or edit the file ~/. bashrc by hand.
To print the entire path, use echo %path% . This will print all directories on a single line separated with semicolons ( ; ) To search / replace a string in a variable, use %path:a=b% which will replace all a characters with b. echo. is used to print a newline.
This is because you're using double quotes, telling your shell to replace $PATH
with the value of the PATH variable before it even starts a.out
.
The wrong value is thus being inserted not by the shell invoked by system()
, but by the shell you're interactively typing commands at.
To fix it, change:
$ ./a.out "echo $PATH"
to:
$ ./a.out 'echo $PATH'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With