Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

echo $PATH in system() give me a wrong output [duplicate]

Tags:

c

linux

shell

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?

like image 618
Terrynini Avatar asked Aug 16 '18 20:08

Terrynini


People also ask

What does echo $PATH print?

echo $PATH doesn't create a variable, it prints the current contents of an already-existing variable.

What is echo $PATH in Linux?

$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.

How do you delete a path variable in Linux?

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.

How do you echo path?

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.


Video Answer


1 Answers

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'
like image 176
Charles Duffy Avatar answered Oct 19 '22 23:10

Charles Duffy