Skip to content

Instantly share code, notes, and snippets.

@savaged
Last active March 22, 2023 07:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save savaged/c473235ad3c64733911099a9018a953e to your computer and use it in GitHub Desktop.
Save savaged/c473235ad3c64733911099a9018a953e to your computer and use it in GitHub Desktop.
Fun with C# and a command line tool for calculating the UNIX file permission number from the text listing
using System.Text.RegularExpressions;
if (args.Length == 0 || !args[0].IsUnixFileModeAndPermissionsString())
{
Console.WriteLine(
"Argument must be in the form of a UNIX file permission string, " +
"i.e. -rwxrwxrwx or -rwxr-xr-x etc.");
return;
}
Console.WriteLine(args[0].ToClasses().ToPermissionNumber());
static class ChmodNumEx
{
public static IEnumerable<string> ToClasses(this string self) =>
new List<string>
{
self[1..4], // group
self[4..7], // other
self[^3..] // user
};
public static int ToPermissionNumber(this IEnumerable<string> self) =>
int.Parse(string.Join("",
self.Select(@class => @class.ToPermissionNumber()).ToList()));
public static bool IsUnixFileModeAndPermissionsString(this string self) =>
new Regex(@"^(-|d|l|p|s|b|c|D)((-|r)(-|w)(-|x)){3}$").IsMatch(self);
private static bool IsPermission(this char self) => self != '-';
private static int ToInt(this bool self) => self ? 1 : 0;
private static int ToPermissionNumber(this string self)
{
var bits = new int[3];
for (var b = 2; b >= 0; b--)
{
bits[b] = self[b].IsPermission().ToInt();
}
return Convert.ToInt16(string.Join("", bits), 2);
}
}
@savaged
Copy link
Author

savaged commented Mar 21, 2023

chmodnum -rwxr--r--

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment