Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Shell Scripting
  • Kali Linux
  • Ubuntu
  • Red Hat
  • CentOS
  • Docker in Linux
  • Kubernetes in Linux
  • Linux interview question
  • Python
  • R
  • Java
  • C
  • C++
  • JavaScript
  • DSA
Open In App
Next Article:
accton command in Linux with Examples
Next article icon

access command in linux with examples

Last Updated : 10 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The ‘access’ command in Linux is a system call used to determine whether the calling process has access to a specified file or directory. This function is useful for checking file permissions, including whether a file exists, and if it can be read, written, or executed by the process. The check is performed using the real user ID (UID) and group ID (GID) of the calling process, making it an essential tool for verifying permissions in various programming and scripting scenarios.

Syntax of the access Function

int access (const char *pathname, int mode);

where,

  • pathname: This argument specifies the path to the file or directory you want to check.
  • mode: This argument specifies the type of access to check for. It can include one or more of the following flags:
    • F_OK flag: Used to check for the existence of a file.
    • R_OK flag: Used to check for read permission bit.
    • W_OK flag: Used to check for write permission bit.
    • X_OK flag: Used to check for execute permission bit.

Return Value:

  • The ‘access’ function returns ‘0’ if the file has the requested access permissions.
  • It returns ‘-1’ if the file does not have the requested permissions or if the file does not exist. In such cases, the global variable ‘errno’ is set to indicate the error.

‘access’ Command Examples in Linux

Let us look at some of the examples of ‘access’ command in Linux to better understand the concept.

Example 1: Checking for File Existence (F_OK Flag)

The first example demonstrates how to use the ‘access’ function to check if a file exists in the current directory using the ‘F_OK’ flag.

#include <stdio.h> #include <unistd.h> #include <errno.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h>  extern int errno;  int main(int argc, const char *argv[]) {     int fd = access("sample.txt", F_OK);     if (fd == -1) {         printf("Error Number: %d\n", errno);         perror("Error Description:");     } else {         printf("No error\n");     }     return 0; } 

Explanation: In the output, we get the message “No error” because the file is present in the current directory. If the file does not exist, the value of fd will become -1. In the above code, the only possible way we will get an error is if the file doesn’t exist for the specified path. It can also give an error if the pathname is too long.

Note: perror() is used to print the error and errno is used to print the error code.

Example 2 : Check for all permission bits (read, write, execute)

The following example demonstrates checking multiple permissions (read, write, and execute) using bitwise OR (|) and bitwise AND (&) operations.

#include <stdio.h> #include <unistd.h> #include <errno.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h>  extern int errno;  int main(int argc, const char *argv[]) {     int fd = access("sample.txt", (R_OK | W_OK) & X_OK);     if (fd == -1) {         printf("Error Number: %d\n", errno);         perror("Error Description:");     } else {         printf("No error\n");     }     return 0; } 

Explanation: In the output, the write and execute user permission bits were set and since we were testing for a case where (R_OK | W_OK) & X_OK, we get no error. The file descriptor value is 0. We can use bitwise operations to decide the mode argument in access () system call.

Example 3: Demonstrating an Error When Required Permissions Are Not Set

Check for all permission bits (read, write, execute) to demonstrate how the code functions, when we get an error.

#include <stdio.h> #include <unistd.h> #include <errno.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h>  extern int errno;  int main(int argc, const char *argv[]) {     int fd = access("sample.txt", R_OK & W_OK & X_OK);     if (fd == -1) {         printf("Error Number: %d\n", errno);         perror("Error Description:");     } else {         printf("No error\n");     }     return 0; } 

Here, fd = -1 and we get the error message for the reason of failure of the calling process.

Explanation: In this example, the program attempts to check for read, write, and execute permissions using the bitwise AND operation. Since the permissions required are strict, the check fails if any of the permissions are missing, resulting in an error. This shows how the ‘access’ function can be used to validate strict access requirements and handle errors appropriately.

Conclusion

The ‘access’ command is a powerful tool in Linux programming for checking file permissions and existence. By utilizing the ‘access’ function, you can ensure your programs and scripts have the necessary permissions to operate on files, and handle errors gracefully when permissions are not met. Its flexibility in checking various permission bits makes it an essential function for developers working with file operations in Linux.


    Next Article
    accton command in Linux with Examples

    R

    redleg
    Improve
    Article Tags :
    • Linux-Unix
    • Technical Scripter
    • Technical Scripter 2018

    Similar Reads

    • Linux Commands
      Linux commands are essential for controlling and managing the system through the terminal. This terminal is similar to the command prompt in Windows. It’s important to note that Linux/Unix commands are case-sensitive. These commands are used for tasks like file handling, process management, user adm
      15+ min read
    • access command in linux with examples
      The 'access' command in Linux is a system call used to determine whether the calling process has access to a specified file or directory. This function is useful for checking file permissions, including whether a file exists, and if it can be read, written, or executed by the process. The check is p
      5 min read
    • accton command in Linux with Examples
      'accton' is one of important Linux/Unix command which is used by the administrator to monitor user activities. It is used to turn on or turn off the process for accounting or change the info process accounting file. When the command is run in the terminal without any argument, it stops the process a
      2 min read
    • aclocal command in Linux with Examples
      aclocal command in Linux is used to automatically generate 'aclocal.m4' files from configure.in file. automake in Linux contain a lot of autoconf macros that can be used in the different packages. These macros must be defined in the aclocal.m4. If not, then it can’t be accessed by the autoconf. The
      3 min read
    • ACPI command in Linux with examples
      ACPI is the command in Linux that helps the users in managing power settings. It also helps in monitoring the hardware status efficiently. It facilitates with providing essential information such as battery health, CPU temperatures, and fan speeds, providing support in system maintenance and perform
      4 min read
    • acpi_available command in Linux with examples
      acpi_available is a command in Linux that tests whether the ACPI (Advanced Configuration and Power Interface) subsystem is available or not. Syntax$ acpi_availableReturn Statuses of acpi_availableThe command returns one of three possible statuses: Status 0: Indicates that the ACPI subsystem is avail
      2 min read
    • acpid command in Linux with Examples
      The acpid daemon provides intelligent power management on a system and allows to query battery and configuration status by supporting the Advanced Configuration and Power Interface (ACPI). The ACPI events are notified to the user-space programs by acpid. The ACPI (Advanced Configuration and Power In
      3 min read
    • addr2line command in Linux with Examples
      'addr2line' command in Linux is used to convert addresses into file names and line numbers. When the executable files/object files are run with the 'objdump' command, the file is de-assembled and the machine code is displayed. These machine instructions for the executable are displayed along with th
      4 min read
    • agetty command in Linux with Examples
      agetty is a Linux version of getty. getty short for "get tty" is a Unix program running on a host computer that manages physical or virtual terminals to allow multi-user access. Linux provides a virtual terminal(tty) which is similar to the regular Linux terminal. agetty command opens a virtual term
      4 min read
    • How to Create and Use Alias Command in Linux
      Imagine you're lost in a maze of complicated Linux commands. You stumble upon a secret doorway marked "Alias," and inside you find shortcuts to all your favorite commands! That's what creating aliases is like. You get to make your own mini-commands for the long ones you use all the time, making thin
      6 min read
    geeksforgeeks-footer-logo
    Corporate & Communications Address:
    A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
    Registered Address:
    K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
    GFG App on Play Store GFG App on App Store
    Advertise with us
    • Company
    • About Us
    • Legal
    • Privacy Policy
    • In Media
    • Contact Us
    • Advertise with us
    • GFG Corporate Solution
    • Placement Training Program
    • Languages
    • Python
    • Java
    • C++
    • PHP
    • GoLang
    • SQL
    • R Language
    • Android Tutorial
    • Tutorials Archive
    • DSA
    • Data Structures
    • Algorithms
    • DSA for Beginners
    • Basic DSA Problems
    • DSA Roadmap
    • Top 100 DSA Interview Problems
    • DSA Roadmap by Sandeep Jain
    • All Cheat Sheets
    • Data Science & ML
    • Data Science With Python
    • Data Science For Beginner
    • Machine Learning
    • ML Maths
    • Data Visualisation
    • Pandas
    • NumPy
    • NLP
    • Deep Learning
    • Web Technologies
    • HTML
    • CSS
    • JavaScript
    • TypeScript
    • ReactJS
    • NextJS
    • Bootstrap
    • Web Design
    • Python Tutorial
    • Python Programming Examples
    • Python Projects
    • Python Tkinter
    • Python Web Scraping
    • OpenCV Tutorial
    • Python Interview Question
    • Django
    • Computer Science
    • Operating Systems
    • Computer Network
    • Database Management System
    • Software Engineering
    • Digital Logic Design
    • Engineering Maths
    • Software Development
    • Software Testing
    • DevOps
    • Git
    • Linux
    • AWS
    • Docker
    • Kubernetes
    • Azure
    • GCP
    • DevOps Roadmap
    • System Design
    • High Level Design
    • Low Level Design
    • UML Diagrams
    • Interview Guide
    • Design Patterns
    • OOAD
    • System Design Bootcamp
    • Interview Questions
    • Inteview Preparation
    • Competitive Programming
    • Top DS or Algo for CP
    • Company-Wise Recruitment Process
    • Company-Wise Preparation
    • Aptitude Preparation
    • Puzzles
    • School Subjects
    • Mathematics
    • Physics
    • Chemistry
    • Biology
    • Social Science
    • English Grammar
    • Commerce
    • World GK
    • GeeksforGeeks Videos
    • DSA
    • Python
    • Java
    • C++
    • Web Development
    • Data Science
    • CS Subjects
    @GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
    We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
    Lightbox
    Improvement
    Suggest Changes
    Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
    geeksforgeeks-suggest-icon
    Create Improvement
    Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
    geeksforgeeks-improvement-icon
    Suggest Changes
    min 4 words, max Words Limit:1000

    Thank You!

    Your suggestions are valuable to us.

    What kind of Experience do you want to share?

    Interview Experiences
    Admission Experiences
    Career Journeys
    Work Experiences
    Campus Experiences
    Competitive Exam Experiences