That’s a great deep dive! The /proc directory is a virtual filesystem. It doesn't exist on your hard drive; instead, the Linux Kernel creates these "files" on the fly in memory to show you what’s happening inside the system.
Here is how /proc/[pid]/cmdline works:
1. What's inside?
Every process on your system has a unique Process ID (PID). For each PID, the kernel creates a directory. The cmdline file inside that directory holds the exact command and arguments used to start that process.
2. The Format (The "Null Byte" Trick)
If you try to read this file with a normal command like cat, it might look a bit weird or run together. That’s because the Kernel separates the arguments using a Null Character (\0) instead of a space.
Example: If you run ./arguments.sh hello world, the cmdline file contains:
./arguments.sh\0hello\0world\0
The Kernel does this so it can handle arguments that have spaces in them without getting confused.
3. How to read it properly
Because of those Null Characters, cat doesn't know how to show it nicely. You can use the tr (translate) command to replace the Nulls with spaces so humans can read it:
# Replace \0 with a newline
cat /proc/self/cmdline | tr '\0' '\n'
(Note: self is a special shortcut that points to the process currently looking at the file—in this case, the cat command itself!)
4. How it connects to your script and $@
- Launch: You type
./arguments.sh hello. - Kernel: The Linux Kernel starts a new process, allocates a PID (let's say 1234), and stores
./arguments.sh\0hello\0in its memory. - ProcFS: The kernel exposes that memory through the virtual file
/proc/1234/cmdline. - Bash: The Bash shell starts running your script. It looks at that memory and populates the special variable
$@so you can easily loop through it.
Try it yourself!
While you are in the terminal, run this command to see how the system sees your current shell:
cat /proc/$$/cmdline | tr '\0' ' '; echo
($$ is a bash variable that automatically holds the PID of your current shell.)
You'll see the command name and every argument you used to log in! This is the "Everything is a file" philosophy in action.