6 ms·
Can you change the current working directory? If not, it's not a shell script.
by xixixao 3mo ago
Can you change the current working directory? If not, it's not a shell script.
- b-kf 3mo agoObviously it's not a shell script, it's still C. It's fun though and being able to freely specify an interpreter/execution path using a shebang has led me to write some useful little command line utilities in unlikely programming languages over the years. That said, not sure why changing the working directory would be the litmus test. A C program can change its own working directory just as easily as an ordinarily executed bash script? $ cat bscript.sh && echo "---" && ./bscript.sh #!/usr/bin/bash cd testdir/ ls --- dummyfile in C you can change dir easily via `chdir()`[1] $ cat cscript && echo "---" && ./cscript #!/usr/bin/tcc -run #include <stdio.h> #include <stdlib.h> #include <unistd.h> int main(void) { if (chdir("testdir") == -1) { perror("chdir"); return EXIT_FAILURE; } execlp("ls", "ls", (char *)NULL); perror("execlp"); return EXIT_FAILURE; } --- dummyfile [1] https://www.man7.org/linux/man-pages/man2/chdir.2.html https://www.man7.org/linux/man-pages/man2/chdir.2.html If you meant somehow changing the parent shell's directory an ordinary bash script doesn't do that either
- zbentley 3mo agoPresumably you can call chdir(2) from the C code? Or did you mean change the directory of the calling shell (in which case, executable shell scripts written in Bash and friends can’t do that either).
- wavemode 3mo agoWell, you can "source" a script, so its effects persist in your current shell session. That's a feature of the script and your shell sharing the same language.
- ivanjermakov 3mo agoOf course you can. How do you think `cd` utility is implemented?
- xigoi 3mo agocd is a shell built-in, not a script.